问题
Im usign the following code to change the icon of selected tab. Im using view pager with 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) {
}
});
the problem is,
- The icon is not being changed though I have changed it.
- When I swipe, it goes to the next tab. But, when I select a tab, the tab is selected but the contents of the tab is not changed and its still the content of the existing tab.
How can I sort this out?
回答1:
To make tab selector and deselector you can use this way
1.Create Custom view and Inflate it:
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.Create drawable Selector
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.Insert in tab:
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));
For individual tab you to have create individual drawable selector and add to tab
来源:https://stackoverflow.com/questions/37650128/unable-to-change-the-tab-icons-while-using-fragmentstatepageradapter