gosulove gosulove - 15 days ago 18
Android Question

setOnTabSelectedListener is deprecated is prompted when creating tab layout

I copied some code from another website. The strange thing is that I always see this 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?

Answer

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 the same way.

General rule of thumb: never use deprecated methods.