Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setOnTabSelectedListener is deprecated

Tags:

android

I always see a crossed out line setOnTabSelectedListener for the following code

viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
    }
}

And the error shown is:

setOnTabSelectedListener is deprecated

However, the program seems to work just fine. May I know what's going on?

like image 916
gosulove Avatar asked Jul 21 '16 08:07

gosulove


3 Answers

May i know whats going on ?

Deprecated means that they decided this is not a good way to do it or they have found a better way of doing it, and this deprecated method will be removed in the future.

The fix is to use addOnTabSelectedListener instead of setOnTabSelectedListener.
It works almost the same way.

The difference is that with addOnTabSelectedListener:

  • you can add multiple listeners. With setOnTabSelectedListener you could only have one.
  • you should remove the listener when you're done with it, with removeOnTabSelectedListener.

General rule of thumb: never use deprecated methods.

like image 175
Tim Avatar answered Oct 15 '22 09:10

Tim


As setOnTabSelectedListener is deprecated now, you can use the new method

addOnTabSelectedListener(OnTabSelectedListener)

This change allows to add multiple tab selection listeners to a single TabLayout.

like image 21
Chol Avatar answered Oct 15 '22 09:10

Chol


in kotlin usage like below code;

   tabLayoutView.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabReselected(p0: TabLayout.Tab?) {
                }

                override fun onTabUnselected(p0: TabLayout.Tab?) {

                }

                override fun onTabSelected(p0: TabLayout.Tab?) {
                    viewPager.currentItem = tabLayoutView.selectedTabPosition
                }


            })
like image 9
Deniz Avatar answered Oct 15 '22 10:10

Deniz