onTabSelected选择未调用

时间:2015-06-17 23:42:21

标签: android tabs

我刚刚将旧的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);

2 个答案:

答案 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());
    }
});

注意:

    每次选项卡发生更改时,都会调用
  • onTabSelectedonTabUnselected
  • 只要在标签显示时再次单击标签,就会调用
  • onTabReselected