在我的应用程序中,我使用ViewPager
。在ViewPager
片段中我使用了第三个片段,但第一个片段内容第一次是空白的,当我从第三个片段返回时,第一个片段内容即将到来。
我搜索过很多信息,但没有什么是清楚的。请问有人给出一个明确的解决方案和一个例子吗?
我的代码:
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
//int limit = (adapter.getCount() > 1 ? adapter.getCount() - 1 : 1);
viewPager = (ViewPager) findViewById(R.id.viewpager);
// viewPager.setOffscreenPageLimit(limit);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabTextColors(Color.parseColor("#313B6f"), Color.parseColor("#313B6f"));
// viewPager.setCurrentItem(2);
}
private void setupViewPager(final ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Selling(), "Selling");
adapter.addFrag(new Buying(), "Buying");
adapter.addFrag(new Watching(), "Watching");
//viewPager.setCurrentItem(2);
viewPager.setAdapter(adapter);
/*viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
Boolean first = true;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (first && positionOffset == 0 && positionOffsetPixels == 0){
onPageSelected(0);
first = false;
}
}
@Override
public void onPageSelected(int position) {
System.out.println("pageee" + position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});*/
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
@Override
public Fragment getItem(int position) {
System.out.println("pageeeitem" + position);
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}