onTabSelected Selected Not Called

后端 未结 2 2147
余生分开走
余生分开走 2020-12-03 09:53

I have just migrated my old ActionBar to new TabLayout ( Support Material Design ).

Everything is great but I can\'t intercept tab selectio

相关标签:
2条回答
  • 2020-12-03 10:11

    Here is a somewhat fuller example with three tabs. It uses the newer addOnTabSelectedListener rather than 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());
        }
    });
    

    Notes:

    • onTabSelected and onTabUnselected are called every time there is a change in tabs.
    • onTabReselected is called whenever a tab is clicked again while it is already showing.
    0 讨论(0)
  • 2020-12-03 10:17

    When you call setupWithViewPager, this will internally call setOnTabSelectedListener(new ViewPagerOnTabSelectedListener(viewPager));, overriding your OnTabSelectedListener.

    Instead, your listener should extend TabLayout.ViewPagerOnTabSelectedListener, then override onTabSelected() and call setOnTabSelectedListener() after 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();
        }
    });
    
    0 讨论(0)
提交回复
热议问题