gosulove gosulove - 3 months ago 169
Android Question

Android setOnTabSelectedListener is depreciated is prompt when creating tab layout

Recently when I working with Tab layout. I copied and pasted some code from another website. The strange thing is that I always see this a crossed out line for the following code

setOnTabSelectedListener


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 depreciated


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

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.