Is there a way to set a particular Tablayout.Tab text color programmatically, without using a state list?

纵然是瞬间 提交于 2019-12-13 03:29:26

问题


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
}


来源:https://stackoverflow.com/questions/48176693/is-there-a-way-to-set-a-particular-tablayout-tab-text-color-programmatically-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!