我刚刚将旧的ActionBar
迁移到新的TabLayout
(支持材料设计)。
一切都很棒,但我不能拦截标签选择
方法onTabSelected
仅在第一次显示TabLayout
时调用,但在单击选项卡时,没有任何反应!
知道这段代码有什么问题吗?
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mViewPager = (ViewPager) findViewById(R.id.pager);
if (mViewPager != null) {
setupViewPager();
}
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
numTab = tab.getPosition();
prefs.edit().putInt("numTab", numTab).apply();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
tabLayout.setupWithViewPager(mViewPager);
答案 0 :(得分:95)
当您致电setupWithViewPager
时,会在内部致电setOnTabSelectedListener(new ViewPagerOnTabSelectedListener(viewPager));
,覆盖您的OnTabSelectedListener
。
相反,您的听众应该延长TabLayout.ViewPagerOnTabSelectedListener,然后覆盖onTabSelected()
并在setOnTabSelectedListener()
之后致电setupWithViewPager()
:
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
@Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
numTab = tab.getPosition();
prefs.edit().putInt("numTab", numTab).apply();
}
});
答案 1 :(得分:2)
这是一个有三个标签的更完整的例子。它使用较新的addOnTabSelectedListener
而不是setOnTabSelectedListener
。
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
Log.i("TAG", "onTabSelected: " + tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
Log.i("TAG", "onTabUnselected: " + tab.getPosition());
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
Log.i("TAG", "onTabReselected: " + tab.getPosition());
}
});
注意:
onTabSelected
和onTabUnselected
。onTabReselected
。