我应该如何选择一个标签在TabLayout编程?
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
我应该如何选择一个标签在TabLayout编程?
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
当前回答
我是这样解决的:
void selectPage(int pageIndex){
tabLayout.setScrollPosition(pageIndex,0f,true);
viewPager.setCurrentItem(pageIndex);
}
其他回答
如果你知道你想要选择的标签的索引,你可以这样做:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
TabLayout.Tab tab = tabLayout.getTabAt(someIndex);
tab.select();
即使你使用TabLayout本身而没有ViewPager(这是非典型的,可能是不好的做法,但我见过这样做),这种技术也是有效的。
这可能不是最终的解决方案,它需要你使用TabLayout和一个ViewPager,但这是我解决它的方法:
void selectPage(int pageIndex)
{
viewPager.setCurrentItem(pageIndex);
tabLayout.setupWithViewPager(viewPager);
}
我测试了使用这段代码对性能的影响有多大,首先在Android Studio中运行该方法时查看CPU和内存监视器,然后将其与我自己在页面之间导航时(使用滑动手势)对CPU和内存的负载进行比较,结果发现差异并不大,所以至少这不是一个可怕的解决方案……
希望这能帮助到一些人!
用这个:
<android.support.design.widget.TabLayout
android:id="@+id/patienthomescreen_tabs"
android:layout_width="match_parent"
android:layout_height="72sp"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabIndicatorColor="@android:color/white"
app:tabSelectedTextColor="@color/green"/>
在OnClickListener中:
TabLayout tabLayout = (TabLayout) findViewById(R.id.patienthomescreen_tabs);
TabLayout.Tab tab = tabLayout.getTabAt(someIndex);
tab.select();
请记住,如果currentTabIndex和index是相同的,那么这将发送您的流到onTabReselected而不是onTabSelected。
Kotlin \用户:
Handler(Looper.getMainLooper()).postDelayed(
{ tabLayout.getTabAt(position).select() }, 100
)
这也将滚动你的标签布局,如果它需要滚动。
用这个:
tabs.getTabAt(index).select();
请记住,如果currentTabIndex和index是相同的,那么这将发送您的流到onTabReselected而不是onTabSelected。