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

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

当前回答

这将不工作的应用程序,有ViewPager2实现,为此,你需要使用

viewPager2.setCurrentItem(position);

当我们使用TabLayoutMediator时,在onConfigureTab中找到onConfigureTab

i.e

TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(
                tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                switch (position){
                    case 0 : tab.setIcon(getResources().getDrawable(R.drawable.camera));
                            break;
                    case 1 : tab.setText("CHAT");
                            viewPager2.setCurrentItem(position); // when app starts this will be the selected tab
                            break;
                    case 2 : tab.setText("STATUS");
                            break;
                    case 3 : tab.setText("CALL");
                        break;
                }
            }
        }
        );
        tabLayoutMediator.attach();

其他回答

最新的简单解决方案对我很有效:

binding.tablayout.selectTab(binding.tablayout.getTabAt(tabPosisiton))

or

with(binding.tablayout) {
    selectTab(getTabAt(tabPosisiton))
}

和tabPosition从0开始

试试这个

    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);

我使用TabLayout切换片段。它在大多数情况下都是有效的,除了当我试图以编程方式使用tab.select(),我的TabLayout选择一个选项卡时。OnTabSelectedListener将触发onTabSelected(TabLayout。Tab Tab),这会让我很伤心。我正在寻找一种不触发侦听器的方法来做程序化选择。

So I adapted @kenodoggy 's answer to my use. I was further facing a problem where some of the internal objects would return null (because they weren't created yet, because I was answering onActivityResult() from my fragment, which occurs before onCreate() in the case the activity is singleTask or singleInstance) so I wrote up a detailed if/else sequence which would report the error and fall through without the NullPointerException that would otherwise trigger. I use Timber for logging, if you're not using that substitute with Log.e().

void updateSelectedTabTo(int position) {
    if (tabLayout != null){
        int selected = tabLayout.getSelectedTabPosition();
        if (selected != -1){
            TabLayout.Tab oldTab = tabLayout.getTabAt(0);
            if (oldTab != null){
                View view = oldTab.getCustomView();
                if (view != null){
                    view.setSelected(false);
                }
                else {
                    Timber.e("oldTab customView is null");
                }
            }
            else {
                Timber.e("oldTab is null");
            }
        }
        else {
            Timber.e("selected is -1");
        }
        TabLayout.Tab newTab = tabLayout.getTabAt(position);
        if (newTab != null){
            View view = newTab.getCustomView();
            if (view != null){
                view.setSelected(false);
            }
            else {
                Timber.e("newTab customView is null");
            }
        }
        else {
            Timber.e("newTab is null");
        }
    }
    else {
        Timber.e("tablayout is null");
    }
}

这里,tabLayout是绑定到XML中的tabLayout对象的内存变量。我不使用滚动标签功能,所以我把它也删除了。

结合不同的答案可以得出:

new Handler().postDelayed(() -> {
  myViewPager.setCurrentItem(position, true);
  myTabLayout.setScrollPosition(position, 0f, true);
},
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.
}

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