如何在TabLayout中获取当前选定的选项卡索引?
问题描述:
当我使用ActionBar标签时,我使用此代码。
When I use ActionBar tabs, I use this code.
private int getCurrentTabIndex() {
ActionBar actionBar = activity.getSupportActionBar();
ActionBar.Tab selectedTab = actionBar.getSelectedTab();
if(selectedTab == null){
return 0;
}
return selectedTab.getPosition();
}
但我怎么能用TabLayout来做呢?
But how can I do it using TabLayout?
答
然后在这个监听器中获取 getPosition()
。
And then in this listener get the getPosition()
.
这样的事情:
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
@Override
public void onTabSelected(TabLayout.Tab tab){
int position = tab.getPosition();
}
});
更新
此方法 setOnTabSelectedListener()
已弃用。 e addOnTabSelectedListener(OnTabSelectedListener)
This method setOnTabSelectedListener()
is deprecated . Use addOnTabSelectedListener(OnTabSelectedListener)