onTabSelected选中未调用
我刚将旧的ActionBar
移植到新的TabLayout
(支持材质devise)中。
一切都很好,但我不能拦截选项卡select方法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);
当你调用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(); } });
这是一个有三个选项卡的更完整的例子。 它使用较新的add OnTabSelectedListener
而不是set OnTabSelectedListener
。
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
被调用,每当一个标签再次被点击时,它已经显示。