Skip to content Skip to sidebar Skip to footer

Is There A Way To Set A Particular Tablayout.tab Text Color Programmatically, Without Using A State List?

The question is how to change a single TabLayout.Tab's text color. Ideally, I'd like to iterate over the tabs and change their color based on information contained on the fragment

Solution 1:

The easiest way is to get the TextView from a specified TabLayout.Tab and then set the text color using TextView.SetTextColor(Color color), which you can do as followed:

TabLayouttabLayout=newTabLayout(this);
intwantedTabIndex=0;

TextViewtabTextView= (TextView)(((LinearLayout)((LinearLayout)tabLayout.GetChildAt(0)).GetChildAt(wantedTabIndex)).GetChildAt(1));

vartextColor= Color.Black;
tabTextView.SetTextColor(textColor);

Solution 2:

(This is a Java answer; hopefully it is helpful despite the fact that you're using Xamarin.)

As far as I can tell, there's no way to do this using public APIs, assuming you're working with the default view created by using a <TabItem> tag or by calling setupWithViewPager(myPager). These ways of creating TabLayout.Tab instances create a package-private TabView mView field (which itself has a private TextView mTextView field). There's no way to get a reference to this TextView, so there's no way to do what you want.

...Unless you're willing to resort to reflection (which means this solution could break at any time). Then you could do something like this:

TabLayouttabs= findViewById(R.id.tabs);

try {
    for (inti=0; i < tabs.getTabCount(); i++) {
        TabLayout.Tabtab= tabs.getTabAt(i);

        FieldviewField= TabLayout.Tab.class.getDeclaredField("mView");
        viewField.setAccessible(true);
        ObjecttabView= viewField.get(tab);

        FieldtextViewField= tabView.getClass().getDeclaredField("mTextView");
        textViewField.setAccessible(true);
        TextViewtextView= (TextView) textViewField.get(tabView);

        textView.setTextColor(/* your color here */);
    }
}
catch (NoSuchFieldException e) {
    // TODO
}
catch (IllegalAccessException e) {
    // TODO
}

Post a Comment for "Is There A Way To Set A Particular Tablayout.tab Text Color Programmatically, Without Using A State List?"