原答案:
Android 团队对 TabLayout 和 ViewPager 相互通信的方式进行了一些更改。阅读文档。但事情并没有得到很好的解释。我在代码中添加了很多注释。我希望这有帮助。
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
Adapter adapter = new Adapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
// the tabs will get their titles from the adapter and get populated
tabLayout.setTabsFromPagerAdapter(adapter);
// this is done "so that the tab position is kept in sync"
// what it does is when you swipe the fragment in view pager, it updates the tabs
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
// without this listener the tabs would still get updated when fragments are swiped, but .... (read the next comment)
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
Toast.makeText(MainActivity.this, "tabSelected: " + tab.getText(), Toast.LENGTH_SHORT).show();
// no where in the code it is defined what will happen when tab is tapped/selected by the user
// this is why the following line is necessary
// we need to manually set the correct fragment when a tab is selected/tapped
// and this is the problem in your code
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
Toast.makeText(MainActivity.this, "tabReSelected: " + tab.getText(), Toast.LENGTH_SHORT).show();
// Reload your recyclerView here
}
});
看看这个issue如果您有任何其他问题。
编辑 1:2015 年 12 月
不是这个问题的解决方案,但总体上有帮助。
tabLayout.setupWithViewPager(viewPager);
这样,您就不必担心在选择选项卡时自己设置片段。tabLayout.setOnTabSelectedListener(..)
在这种情况下不再需要。就是这样处理的在引擎盖下。当您不需要对选项卡进行太多控制时(例如在选择/点击同一选项卡时重新加载片段),这非常有用。
更新:2018 年 5 月
tabLayout.setTabsFromPagerAdapter(adapter);
tabLayout.setOnTabSelectedListener(...);
上述两个函数均已弃用。初始化viewpager+tablayout如下图:
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager); // this will automatically bind tab clicks to viewpager fragments
viewPager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabLayout))
// do additional tab clicks here
// no need to manually set viewpager item based on tab click
tabLayout.addOnTabSelectedListener(...);