How to get the current selected item position using TabLayout in Android Design Library

7.4k views Asked by At

I am using the android design library TabLayout in that how can I get the current selected item tab position.

  ViewPager pager = (ViewPager) view.findViewById(R.id.pager);      
  MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
  pager.setAdapter(adapter);
  tabLayout.setupWithViewPager(pager);
4

There are 4 answers

1
Niklas On BEST ANSWER

As of version 22.2.1 of the Support library the TabLayout has a method getSelectedTabPosition.

Source 1 | Source 2

2
Bryan Herbst On

You can call ViewPager's getCurrentItem() to get the index of the currently displayed item.

2
Moinkhan On

[Updated 29-07-2016]

Refer the accepted answer because below answer is deprecated. If you are using older version then refer it.

You can do it easily ...

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    pos = tab.getPosition();
                }

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

                }

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

                }
            });
0
DoronK On
  mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            int position = tab.getPosition();
        }

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

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