Is there a way to set a particular Tablayout.Tab t

2019-08-21 02:36发布

问题:

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 of a corresponding ViewPager.

回答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:

TabLayout tabLayout = new TabLayout(this);
int wantedTabIndex = 0;

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

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


回答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:

TabLayout tabs = findViewById(R.id.tabs);

try {
    for (int i = 0; i < tabs.getTabCount(); i++) {
        TabLayout.Tab tab = tabs.getTabAt(i);

        Field viewField = TabLayout.Tab.class.getDeclaredField("mView");
        viewField.setAccessible(true);
        Object tabView = viewField.get(tab);

        Field textViewField = tabView.getClass().getDeclaredField("mTextView");
        textViewField.setAccessible(true);
        TextView textView = (TextView) textViewField.get(tabView);

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