Android: Change Tab Text Color Programmatically

后端 未结 4 1696
星月不相逢
星月不相逢 2020-11-30 09:08

I\'ve a TabHost like this:


 

        
相关标签:
4条回答
  • 2020-11-30 09:23

    When you use findViewById(id) you ask the system to look for any View with the id "id" relatively to the current ViewGroup. That means that what you do in your code is this.findViewById(id), so it will look for "id" in the current View. And doing findViewById(android.R.id.tabHost) is not very smart because it just does not exist...

    When you do getTabHost() however, you ask the system to get the unique tabHost of your activity, no matter it have any View as root, i.e. the tabHost can be attached to nothing upside it.

    As a conclusion, you should always us getTabHost in your TabHostActivity

    Hope I was clear

    0 讨论(0)
  • 2020-11-30 09:33

    For me @Farhan 's solution did not work since getChildCount() kept returning 1 while having four tabs. Using getTabCount() and getChildTabViewAt() solved it for me:

    for (int tabIndex = 0 ; tabIndex < mTabHost.getTabWidget().getTabCount() ; tabIndex ++) {
        View tab = mTabHost.getTabWidget().getChildTabViewAt(tabIndex);
        TextView t = (TextView)tab.findViewById(android.R.id.title);
        t.setTextColor(getResources().getColor(R.color.white));
    }
    

    I'd thought I post this alternative for people having the same issue.

    0 讨论(0)
  • 2020-11-30 09:40

    For the new design support tab layout; you can define it in your xml
    app:tabTextColor="@color/tab_inactive" app:tabSelectedTextColor="@color/tab_active"
    E.g. -

    <android.support.design.widget.TabLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/tabanim_tabs"
                app:tabTextColor="@color/tab_inactive"
                app:tabSelectedTextColor="@color/tab_active"
                android:textAllCaps="false"
                />
    


    Programatically it may be acheived like this:

    tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.color.tab_selector));
            tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator));
    
    0 讨论(0)
  • 2020-11-30 09:42

    To change the text color of tabs, you need to get the view i.e TextView which is set as title of tabs and you can change it like this:

        TabHost tabhost = getTabHost();
        for(int i=0;i<tabhost.getTabWidget().getChildCount();i++) 
        {
            TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
            tv.setTextColor(.....);
        } 
    

    hope this helps....

    0 讨论(0)
提交回复
热议问题