我正在使用带有ViewPager的tablayout,我有3个标签,并且我使用片段作为我的标签。问题是,当我转到标签3时,标签1的内容完全丢失,需要重新加载,我不想要这样的东西,我想让它们保存数据而且它没有&# 39;需要重新加载。
这是我的代码:
private void setupViewPager(ViewPager viewPager) {
Bundle bl = getIntent().getExtras();
Bundle bundle = new Bundle();
bundle.putString("for", bl.getString("for"));
if (bl.getString("for").equals("catid"))
bundle.putString("catid", bl.getString("catid"));
Bundle bundle2 = new Bundle();
bundle2.putString("for", bl.getString("for"));
if (bl.getString("for").equals("catid"))
bundle2.putString("catid", bl.getString("catid"));
Bundle bundle3 = new Bundle();
bundle3.putString("for", bl.getString("for"));
if (bl.getString("for").equals("catid"))
bundle3.putString("catid", bl.getString("catid"));
FragmentList latest = new FragmentList();
bundle.putString("forw","latest");
latest.setArguments(bundle);
FragmentList topvisit = new FragmentList();
bundle2.putString("forw","topvisit");
topvisit.setArguments(bundle2);
FragmentList por_mabhas = new FragmentList();
bundle3.putString("forw","por_mabhas");
por_mabhas.setArguments(bundle3);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(por_mabhas, "پرمبحث ترین خبرها");
adapter.addFragment(topvisit, "پربازدیدترین اخبار");
adapter.addFragment(latest, "تازه ترین خبرها");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private void declare() {
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
final int finalPos = 2;
tabLayout.post(new Runnable() {
@Override
public void run() {
int right = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(finalPos).getRight();
tabLayout.scrollTo(right,0);
tabLayout.getTabAt(finalPos).select();
}
});
}
我该怎么办?
答案 0 :(得分:1)
使用setOffscreenPageLimit(TOTAL_PAGE);
如果您有N个页面,则可以使用此页面,以便将所有页面保留在内存中。
viewpager.setOffscreenPageLimit(TOTAL_PAGE);