我应该如何选择一个标签在TabLayout编程?
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
我应该如何选择一个标签在TabLayout编程?
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
当前回答
最新的简单解决方案对我很有效:
binding.tablayout.selectTab(binding.tablayout.getTabAt(tabPosisiton))
or
with(binding.tablayout) {
selectTab(getTabAt(tabPosisiton))
}
和tabPosition从0开始
其他回答
对于材质组件库提供的TabLayout,只需使用selectTab方法:
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.selectTab(tabLayout.getTabAt(index));
它需要版本为1.1.0。
TabLayout jobTabs = v.findViewById(R.id.jobTabs);
ViewPager jobFrame = v.findViewById(R.id.jobPager);
jobFrame.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(jobTabs));
这将选择标签作为视图分页器滑动页面
如果你不能使用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在选中和未选中的可绘制对象之间切换,或者类似地处理颜色和/或可绘制对象。
我是这样解决的:
void selectPage(int pageIndex){
tabLayout.setScrollPosition(pageIndex,0f,true);
viewPager.setCurrentItem(pageIndex);
}
只需设置viewpage . setcurrentitem (index)和相关的TabLayout将选择各自的选项卡。