44

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.

jay
  • 1,982
  • 2
  • 24
  • 54

8 Answers8

82

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.

Manpreet Singh
  • 1,048
  • 7
  • 7
12

Use the ViewPager.onPageChangeListener:

mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
}
Abhishek Singh
  • 9,008
  • 5
  • 28
  • 53
  • how to skip first one? it is called on app launch, but I want `onPageSelected` to be called when a user pressed the tab button – user924 Aug 02 '22 at 14:31
  • found a solution for my needs, we can use `binding.tabLayout.addOnTabSelectedListener` instead – user924 Aug 02 '22 at 14:35
10

You can use addOnTabSelectedListener method:

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
            if (tab.getPosition() == 0) {
                toolBarTitle.setText("Tab one");
            } else if (tab.getPosition() == 1) {
                toolBarTitle.setText("Tab two");
            } else {
                toolBarTitle.setText("Tab three");
            }
        }

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

        }

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

        }
    });
Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
5

Tab change listener for kotlin lover

tab_selector_layout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
        override fun onTabSelected(tab: TabLayout.Tab?) {
            
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {
            
        }

        override fun onTabReselected(tab: TabLayout.Tab?) {
            
        }

    })
code4rox
  • 941
  • 9
  • 34
2

From the Documentation

You need to implement TabLayout.OnTabSelectedListener

    public class HomeActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener

override the following the method to listen for event:

 @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) {

    }
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
1

You should implement OnTabChangeListener to the TabActivity class rather than the contents of the Tab.

In your TabActivity implement OnTabChangeListener

then set the listener for the TabHost mTabHost.setOnTabChangedListener(this);

Ex.1

@Override
public void onTabChanged(String tabId) {
    Log.i("selected tab ", tabId);

}

Ex.2

  public class HelloTabWidget extends TabActivity implements OnTabChangeListener{

private TabHost mTabHost;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Resources res = getResources(); 
    TabHost tabHost = getTabHost();  
    TabHost.TabSpec spec;  
    Intent intent; 
    mTabHost = getTabHost();


    intent = new Intent().setClass(this, BarActivity.class);
    spec = tabHost.newTabSpec("Name").setIndicator("Name",res.getDrawable(R.drawable.ic_tab_name)).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, CityActivity.class);
    spec = tabHost.newTabSpec("city").setIndicator("City",res.getDrawable(R.drawable.ic_tab_city)).setContent(intent); 
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, MapsActivity.class);
    spec = tabHost.newTabSpec("Country").setIndicator("Country",res.getDrawable(R.drawable.ic_tab_map)).setContent(intent);
    tabHost.addTab(spec);        

    tabHost.setCurrentTab(2);
    mTabHost.setOnTabChangedListener(this);
}

public void onTabChanged(String tabId) {
    Toast.makeText(getApplicationContext(), "Selected Tab "+tabId, Toast.LENGTH_LONG).show();
    Log.i("selected tab index", "Current index - "+ mTabHost.getCurrentTab());      
}} 
0

Depends on what you want. If you just want to know if the tab page changes, or find out which tab position was selected, use:

mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
    public void onPageScrollStateChanged(int state) {

    }
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    public void onPageSelected(int position) {

    }
});

Else, if you want to keep track of the tab itself, you will have to implement TabLayout.OnTabSelectedListener like this:

public class HomeActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener

And add this methods to your HomeActivity class:

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

}

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

}

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

}
0
tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
           @Override
           public void onTabSelected(TabLayout.Tab tab) {

               viewpager.setCurrentItem(tab.getPosition());

               if (tab.getPosition() == 6 || tab.getPosition() == 11 )

                   if (mInterstitialAd.isLoaded()) {
                       mInterstitialAd.show();

                   }
           }
  • This question already contains multiple answers and an accepted answer. Can you explain (by editing your answer) where your answer differs from the other answers? Also know that Code-only answers are not useful in the long run. – 7uc1f3r Jan 11 '21 at 07:58