我应该如何选择一个标签在TabLayout编程?

 TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
 tabLayout.setupWithViewPager(viewPager);

当前回答

试试这个方法。

tabLayout.setTabTextColors(getResources().getColor(R.color.colorHintTextLight),
                           getResources().getColor(R.color.colorPrimaryTextLight));

其他回答

对于Viewpager2, Kotlin,其他答案都没有帮助,只有下面这个有用。位置是从片段结果监听器在我的情况下:

TabLayoutMediator(binding.tabLayout, binding.viewPager2) { _, _ ->
    binding.viewPager2 = position
}.attach()

只需设置viewpage . setcurrentitem (index)和相关的TabLayout将选择各自的选项卡。

试试这个

    new Handler().postDelayed(
            new Runnable(){
                @Override
                public void run() {
                    if (i == 1){
                        tabLayout.getTabAt(0).select();
                    } else if (i == 2){
                        tabLayout.getTabAt(1).select();
                    }
                }
            }, 100);

如果碰巧你的默认选项卡是第一个(0),而你碰巧切换到一个片段,那么你必须手动替换第一次的片段。这是因为在注册侦听器之前选择了选项卡。

private TabLayout mTabLayout;

...

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_tablayout, container, false);
    mTabLayout = view.findViewById(R.id.sliding_tabs);
    mTabLayout.addOnTabSelectedListener(mOnTabSelectedListener);

    getActivity().getSupportFragmentManager().beginTransaction()
        .replace(R.id.tabContent, MyFirstFragment.newInstance()).commit();
    return view;
}

或者,你可以考虑调用getTabAt(0).select()并像这样重写onTabReselected:

@Override
public void onTabReselected(TabLayout.Tab tab) {
    // Replace the corresponding tab fragment.
}

这是可行的,因为你实际上是在每个选项卡重新选择上替换片段。

对于材质组件库提供的TabLayout,只需使用selectTab方法:

TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.selectTab(tabLayout.getTabAt(index));

它需要版本为1.1.0。