这是我的tabLayoutCode
mTabLayoutBerita.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
Log.i("onTabSelected", String.valueOf(tab.getPosition()));
mViewPagerBerita.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
这是在我的PagerAdapter中
public class PagerBerita extends FragmentPagerAdapter {
private int mNumOfTabs;
private FragmentBeritaByKategori fragmentBeritaByKategori = null;
private List<KategoriItem> mDataListKategoriBerita;
public PagerBerita(FragmentManager fm, int NumOfTabs, List<KategoriItem> mDataListKategoriBerita) {
super(fm);
this.mNumOfTabs = NumOfTabs;
this.mDataListKategoriBerita = mDataListKategoriBerita;
}
@Override
public Fragment getItem(int position) {
fragmentBeritaByKategori = new FragmentBeritaByKategori(mDataListKategoriBerita.get(position).getId());
return fragmentBeritaByKategori;
}
@Override
public int getCount() {
return mDataListKategoriBerita.size();
}
}
我正在尝试创建动态选项卡布局,但是当该选项卡已经显示时,我得到了错误的数据,因为我在PagerAdapter中使用的位置是错误的。我已经使用过setOffscreenPageLimit并且无法正常工作,我很困惑。这种情况有什么解决办法吗?非常感谢。
最佳答案
You are forgot to add ViewPager to tab layout.
TabLayout tabsLayout = (TabLayout) findViewById(R.id.tabsLayout);
ViewPager viewpager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
//Add ViewPager to tab layout.
tabsLayout.setupWithViewPager(viewpager);
viewpager.setOffscreenPageLimit(8);
tabsLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewpager.setCurrentItem(tab.getPosition());
Log.i("TabLayout Position: " + tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
It working fine.
关于android - ViewPager.setCurrentItem在PagerAdapter中返回错误的位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49686458/