Tab change listener android

jay picture jay · Mar 27, 2017 · Viewed 34.4k times · Source

My HomeActivity extends AppCompatActivity that uses 2 tabs.

public class HomeActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private TabLayout tabLayout;
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ...
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
    }

    ...

How to listen to tab change event? Let me know if I need to add any more code for clarity.

Answer

Manpreet Singh picture Manpreet Singh · Mar 27, 2017

You can use OnTabChangeListener.See below

    TabLayout tabLayout = new TabLayout(this);
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            //do stuff here
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

hope it help.