我应该如何选择一个标签在TabLayout编程?
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
我应该如何选择一个标签在TabLayout编程?
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
当前回答
如果你不能使用tab.select(),也不想使用ViewPager,你仍然可以通过编程方式选择一个选项卡。如果你通过TabLayout使用自定义视图。选项卡setCustomView (android.view。View View)它更简单。以下是如何做到这两种方式。
// if you've set a custom view
void updateTabSelection(int position) {
// get the position of the currently selected tab and set selected to false
mTabLayout.getTabAt(mTabLayout.getSelectedTabPosition()).getCustomView().setSelected(false);
// set selected to true on the desired tab
mTabLayout.getTabAt(position).getCustomView().setSelected(true);
// move the selection indicator
mTabLayout.setScrollPosition(position, 0, true);
// ... your logic to swap out your fragments
}
如果你不使用自定义视图,那么你可以这样做
// if you are not using a custom view
void updateTabSelection(int position) {
// get a reference to the tabs container view
LinearLayout ll = (LinearLayout) mTabLayout.getChildAt(0);
// get the child view at the position of the currently selected tab and set selected to false
ll.getChildAt(mTabLayout.getSelectedTabPosition()).setSelected(false);
// get the child view at the new selected position and set selected to true
ll.getChildAt(position).setSelected(true);
// move the selection indicator
mTabLayout.setScrollPosition(position, 0, true);
// ... your logic to swap out your fragments
}
使用StateListDrawable在选中和未选中的可绘制对象之间切换,或者类似地处理颜色和/或可绘制对象。
其他回答
如果你知道你想要选择的标签的索引,你可以这样做:
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和内存的负载进行比较,结果发现差异并不大,所以至少这不是一个可怕的解决方案……
希望这能帮助到一些人!
如果你正在使用TabLayout和viewPager,那么这有助于你。你可以在addOnpagelistener中使用ViewPager设置TabLayout。
如果你想直接设置TabLayout的位置(不是点击Tab个人)试试下面的代码TabLayout . gettabat (position_you_want_to_set).select()
/* will be invoked whenever the page changes or is incrementally scrolled*/
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
tabLayout.getTabAt(position).select();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
用这个:
tabs.getTabAt(index).select();
请记住,如果currentTabIndex和index是相同的,那么这将发送您的流到onTabReselected而不是onTabSelected。
最新的简单解决方案对我很有效:
binding.tablayout.selectTab(binding.tablayout.getTabAt(tabPosisiton))
or
with(binding.tablayout) {
selectTab(getTabAt(tabPosisiton))
}
和tabPosition从0开始