我在我的Android项目中使用了FragementStateAdapter和ViewPager2。但问题是我的片段在标签更改时被重新加载。我想阻止它怎么做?我已经尝试了许多在线方法,如指定setOffScreenLimit等,但没有什么对我不起作用。这是我的代码
下面是我的适配器代码
public class LandingAdapter extends FragmentStateAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
public LandingAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
@NonNull
@Override
public Fragment createFragment(int position) {
return mFragmentList.get(position);
}
@Override
public int getItemCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
@Override
public long getItemId(int position) {
return mFragmentList.get(position).hashCode();
}
}
这是我的活动代码
ViewPager2 mViewPager = findViewById(R.id.ViewPager);
TabLayout mTabLayout = findViewById(R.id.TabLayout);
LandingAdapter mAdapter = new LandingAdapter(getSupportFragmentManager(), getLifecycle());
mViewPager.setAdapter(mAdapter);
int savedAppMode = SharedPrefs.getInt(this, "app_mode_checked_item",0);
if (savedAppMode == 1) {
mAdapter.addFragment(new ItemsFrag1());
mAdapter.addFragment(new ContactsFrag1());
mAdapter.addFragment(new ImagesFrag1());
} else {
mAdapter.addFragment(new ItemsFrag2());
mAdapter.addFragment(new ContactsFrag2());
mAdapter.addFragment(new ImagesFrag2());
}
new TabLayoutMediator(mTabLayout, mViewPager, (tab, position) -> {
switch (position) {
case 0:
tab.setText("Items");
tab.setIcon(R.drawable.x_icon_photo);
break;
case 1:
tab.setText("Contacts");
tab.setIcon(R.drawable.x_icon_video);
break;
case 2:
tab.setText("Images");
tab.setIcon(R.drawable.x_icon_download);
break;
}
}).attach();
1条答案
按热度按时间knpiaxh11#
您需要在使用FragmentPagerAdapter的片段的onCreate()中调用setRetainInstance(true)。
或者
你可以用limit