我的应用中的标签出现问题。当我选择一个标签时,我想更改其图标和文字颜色。当我更改为另一个选项卡时,图标和文本颜色需要更改为中性色。
我尝试这样做,但是当图标确实改变时,文本颜色保持不变。
final TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.addTab(tabs.newTab().setIcon(R.mipmap.destacados_act).setText("Destacados"));
tabs.setSelectedTabIndicatorColor(Color.rgb(255,170,0));
tabs.addTab(tabs.newTab().setIcon(R.mipmap.secciones).setText("Secciones"));
tabs.addTab(tabs.newTab().setIcon(R.mipmap.descargas).setText("Descargas"));
final ViewPager view_pager = (ViewPager) findViewById(R.id.pager);
final ViewPagerAdapterPrincipal adapter = new ViewPagerAdapterPrincipal(getSupportFragmentManager(), tabs.getTabCount());
view_pager.setAdapter(adapter);
view_pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabs));
tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
view_pager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
tab.setIcon(R.mipmap.destacados_act);
tabs.setSelectedTabIndicatorColor(Color.rgb(255,170,0));
break;
case 1:
tab.setIcon(R.mipmap.secciones_act);
tabs.setSelectedTabIndicatorColor(Color.rgb(0,255,255));
break;
case 2:
tab.setIcon(R.mipmap.descargas_act);
tabs.setSelectedTabIndicatorColor(Color.rgb(170,255,0));
break;
}
}
public void onTabUnselected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
tab.setIcon(R.mipmap.destacados);
break;
case 1:
tab.setIcon(R.mipmap.secciones);
break;
case 2:
tab.setIcon(R.mipmap.descargas);
break;
}
}
public void onTabReselected(TabLayout.Tab tab) {
}
});
这是我的适配器代码
public class ViewPagerAdapterPrincipal extends FragmentStatePagerAdapter {
int numOfTabs;
public ViewPagerAdapterPrincipal(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
public Fragment getItem(int position) {
switch(position){
case 0 :
DestacadosPrincipal tab1 = new DestacadosPrincipal();
return tab1;
case 1 :
Secciones tab2 = new Secciones();
return tab2;
case 2 :
Descargas tab3 = new Descargas();
return tab3;
default:
return null;
}
}
public int getCount() {
return numOfTabs;
}
}
问题来了
OnTabUnselected
如果我删除了
tab.setIcon();
文字颜色很好但显然图标没有变化。
答案 0 :(得分:1)
您可以使用选择器
在选项卡上为TextView设置样式这假设您使用了包含带有style =“@ style / tabText”的TextView的自定义选项卡布局。
<强>值/ styles.xml 强>
contentInset
然后使用选择器设置textColor:
<强>抽拉/ text_selector_tab.xml 强>
UISearchBarController
然后为选定和未选择状态设置颜色属性(即此处显示为colorSelected和colorDeselected。
您可以使用自定义布局自定义标签:
<style name="tabText">
<item name="android:textColor">@drawable/text_selector_tab</item>
<item name="android:textSize">@dimen/fontTab</item>
<item name="android:textAllCaps">true</item>
</style>
<强>布局/ layout_tab.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="@color/colorSelected" />
<item android:color="@color/colorDeselected" />
</selector>
这就是选项卡中的TextView如何与样式绑定。您可以深入了解平台SDK中的标准选项卡布局XML,以查看图标和文本的工作方式,并相应地调整此布局。