TabLayout选项卡选择

问题描述:

如何以编程方式在TabLayout中选择一个标签?

How should I select a tab in TabLayout programmatically?

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

如果知道要选择的选项卡的索引,则可以这样做:

If you know the index of the tab you want to select, you can do it like so:

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
TabLayout.Tab tab = tabLayout.getTabAt(someIndex);
tab.select();

即使您单独使用TabLayout而不使用ViewPager,此技术也可以工作(这是非典型的,可能是不好的做法,但我已经看到了).

This technique works even if you're using the TabLayout by itself without a ViewPager (which is atypical, and probably bad practice, but I've seen it done).