我在ViewPager中使用TabLayout,我也必须听TabReselected事件,但似乎它们是冲突的:
mViewPager.setAdapter(...);
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
Toast.makeText(getActivity(), "selected...", Toast.LENGTH_LONG).show();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
Toast.makeText(getActivity(), "reselected...", Toast.LENGTH_LONG).show();
}
});
mTabLayout.setupWithViewPager(mViewPager);
似乎当我使用setupWithViewPager(mViewPager)时,之前添加的Listener将无效。关键是当标签是[[重新选择]]时我需要做其他事情,但是如何?
答案 0 :(得分:1)
//使用runnable,因为使用viewpager进行设置需要时间:
viewPager.setAdapter(viewpagerAdapter);
tabLayout.post(new Runnable() {
@Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
Toast.makeText(MainActivity.this, "selected...", Toast.LENGTH_LONG).show();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
Toast.makeText(MainActivity.this, "reselected...", Toast.LENGTH_LONG).show();
}
});
}
});
答案 1 :(得分:0)
您需要做的是,首先需要致电
tabLayout.setupWithViewPager(onBoardVP);
然后在onTabSelected()
方法中添加mViewPager.setCurrentItem(tab.getPosition());
就像这样:
@Override
public void onTabSelected(TabLayout.Tab tab) {
Toast.makeText(MainActivity.this, "selected...", Toast.LENGTH_LONG).show();
mViewPager.setCurrentItem(tab.getPosition());
}