我使用 FragmentStateAdapter
、ViewPager2
和 com.google.android.material.tabs.TabLayout
,为了设置选项卡图标,我使用 com.google.android.material.tabs.TabLayoutMediator
TabLayoutMediator(
mTabActivity.tabLayout,
mTabActivity.viewPager,
TabLayoutMediator.TabConfigurationStrategy { tab, position ->
when (mTabEnums[position]) {
TabType.TAB_CONTACT -> tab.setIcon(R.drawable.ic_tab_contact)
TabType.TAB_GROUPS -> tab.setIcon(R.drawable.ic_tab_groups)
TabType.TAB_MESSAGES -> tab.setIcon(R.drawable.ic_tab_message)
TabType.TAB_MAPS -> tab.setIcon(R.drawable.ic_tab_map)
TabType.TAB_RECENTS -> tab.setIcon(R.drawable.ic_tab_recent)
TabType.TAB_INCALL_LIST -> tab.setIcon(R.drawable.ic_tab_contact)
TabType.TAB_INCALL_MAPS -> tab.setIcon(R.drawable.ic_tab_map)
}
}
).attach()
但是我怎么改变选定选项卡的图标呢?
我尝试过这个方法,但是mViewPager
是一个ViewPager2
而不是ViewPager
,代码无法编译。
mTabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
@Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
int tabIconColor = ContextCompat.getColor(
ActivityTab.this, R.color.colorPrimary);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
int tabIconColor = ContextCompat.getColor(
ActivityTab.this, R.color.colorAccent);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
super.onTabReselected(tab);
}
}
);