我应该如何选择一个标签在TabLayout编程?
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
我应该如何选择一个标签在TabLayout编程?
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
当前回答
如果您在理解上有困难,这段代码可以帮助您
private void MyTabLayout(){
TabLayout.Tab myTab = myTabLayout.newTab(); // create a new tab
myTabLayout.addTab(myTab); // add my new tab to myTabLayout
myTab.setText("new tab");
myTab.select(); // select the new tab
}
你也可以在你的代码中添加这个:
myTabLayout.setTabTextColors(getColor(R.color.colorNormalTab),getColor(R.color.colorSelectedTab));
其他回答
对于Viewpager2, Kotlin,其他答案都没有帮助,只有下面这个有用。位置是从片段结果监听器在我的情况下:
TabLayoutMediator(binding.tabLayout, binding.viewPager2) { _, _ ->
binding.viewPager2 = position
}.attach()
用这个:
<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。
如果你正在使用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) {
}
});
有点晚了,但可能是一个有用的解决方案。 我直接在我的片段中使用我的TabLayout,并试图在片段的生命周期中选择一个选项卡。 对我来说有用的是等待TabLayout使用android.view绘制完它的子视图。视图# post方法。即:
int myPosition = 0;
myFilterTabLayout.post(() -> { filterTabLayout.getTabAt(myPosition).select(); });
您可以使用以下函数设置TabLayout位置
public void setTab(){
tabLayout.setScrollPosition(YOUR_SCROLL_INDEX,0,true);
tabLayout.setSelected(true);
}