不推荐使用setOnTabSelectedListener [英] setOnTabSelectedListener is deprecated
问题描述
对于以下代码,我总是看到划线 setOnTabSelectedListener
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());
}
}
显示的错误是:
setOnTabSelectedListener已弃用
setOnTabSelectedListener is deprecated
但是,该程序似乎正常运行.我可以知道发生了什么吗?
However, the program seems to work just fine. May I know what's going on?
推荐答案
我能知道发生了什么吗?
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.
解决方法是使用 setOnTabSelectedListener .
它的工作方式几乎相同.
The fix is to use addOnTabSelectedListener instead of setOnTabSelectedListener.
It works almost the same way.
不同之处在于,使用 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.
这篇关于不推荐使用setOnTabSelectedListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!