写一个demo时发现,其中TabLayout作为底部导航栏,默认选中竟然无法回调onTabSelected,而选择其他Position时,可以正常回调回来
原因是因为我们是先addTab这个时候还没有绑定回调方法,所以应该是先是设置回调,而后add
mTabLayout = findViewById(R.id.tab_layout);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
Log.d("调试", "onTabSelected: " + tab.getPosition());
tab.getIcon().setColorFilter(getResources().getColor(R.color.deep_orange_500), PorterDuff.Mode.SRC_IN);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.ReplacePage,FragmentManage.getsInstance().getFragment(tab.getPosition()));
transaction.commit();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(getResources().getColor(R.color.grey_60), PorterDuff.Mode.SRC_IN);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mTabLayout.addTab(mTabLayout.newTab().setIcon(R.drawable.ic_baseline_home_24),0);
mTabLayout.addTab(mTabLayout.newTab().setIcon(R.drawable.ic_baseline_free_fan_24),1);
mTabLayout.addTab(mTabLayout.newTab().setIcon(R.drawable.ic_baseline_category_24),2);
mTabLayout.addTab(mTabLayout.newTab().setIcon(R.drawable.ic_baseline_person_24),3);
// set icon color pre-selected
mTabLayout.getTabAt(0).getIcon().setColorFilter(getResources().getColor(R.color.deep_orange_500), PorterDuff.Mode.SRC_IN);
mTabLayout.getTabAt(1).getIcon().setColorFilter(getResources().getColor(R.color.grey_60), PorterDuff.Mode.SRC_IN);
mTabLayout.getTabAt(2).getIcon().setColorFilter(getResources().getColor(R.color.grey_60), PorterDuff.Mode.SRC_IN);
mTabLayout.getTabAt(3).getIcon().setColorFilter(getResources().getColor(R.color.grey_60), PorterDuff.Mode.SRC_IN);
mTabLayout.getTabAt(0).select();
这就解决了