我使用以下代码更改所选标签的图标。我正在使用带有FragmentStatePagerAdapter的视图寻呼机。
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
viewPager.setSelected(true);
tab.setIcon(R.drawable.status);
} else if (tab.getPosition() == 1){
tab.setIcon(R.drawable.status);
viewPager.setSelected(true);
}else if (tab.getPosition() == 2){
tab.setIcon(R.drawable.status);
viewPager.setSelected(true);
}else if (tab.getPosition() == 3){
tab.setIcon(R.drawable.ic_menu_share);
viewPager.setSelected(true);
}
//also you can use tab.setsetCustomView() too
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
tab.setIcon(R.drawable.status_inactive);
viewPager.setSelected(false);
} else if (tab.getPosition() == 1){
tab.setIcon(R.drawable.rating_inactive);
viewPager.setSelected(false);
}else if (tab.getPosition() == 2){
tab.setIcon(R.drawable.photos_inactive);
viewPager.setSelected(false);
}else if (tab.getPosition() == 3){
tab.setIcon(R.drawable.ic_menu_share);
viewPager.setSelected(false);
}
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
问题是,
我该如何解决这个问题?
答案 0 :(得分:1)
要制作标签选择器和取消选择器,您可以使用这种方式
1.创建自定义视图并对其进行充气:
private View getTabView(int imgDrawable) {
View view = getLayoutInflater().inflate(R.layout.tab_view, null);
ImageView imgTab = (ImageView) view.findViewById(R.id.imgTab);
imgTab.setImageDrawable(getResources().getDrawable(imgDrawable));
return view;
}
2.创建可绘制选择器
tab_home_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_home_selected" android:state_selected="true" />
<item android:drawable="@drawable/ic_home_deselected" />
</selector>
3.插入标签:
tabDashboardLayout = (TabLayout) findViewById(R.id.tabDashboardLayout);
//Adding the tabs using addTab() method
View tabView = getTabView(R.drawable.tab_home_selector);;
tabDashboardLayout.addTab(tabDashboardLayout.newTab().setCustomView(tabView));
对于单个标签,您可以创建单独的可绘制选择器并添加到标签