我试图实现ViewPager + Adapter,在清单中没有configChanges,结果:
当我旋转屏幕时,片段视图变为空,并删除仅显示一个选项卡的其他视图
我的适配器
private class TabsPagerAdapter extends FragmentStatePagerAdapter {
private Bundle bundle;
private String titulo;
private List<LeiAberta> fragments;
private TabsPagerAdapter(FragmentManager fm) {
super(fm);
fragments = new ArrayList<>();
}
@Override
public LeiAberta getItem(int position) {
return fragments.get(position);
}
private void addPage(LeiAberta page) {
page.setRetainInstance(true);
fragments.add(page);
notifyDataSetChanged();
}
public void removePage(int position) {
if(fragments.size() <= 1) {
finish();
} else {
fragments.remove(position);
notifyDataSetChanged();
}
}
@Override
public int getItemPosition(Object object) {
if (fragments.contains(object)) return fragments.indexOf(object);
else
return POSITION_NONE;
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
this.bundle = fragments.get(position).getArguments();
if (this.bundle != null) {
this.titulo = bundle.getString("titulo");
}
return titulo;
}
}
创建活动时:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leitura);
tabs = (TabLayout) findViewById(R.id.tabs);
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setOffscreenPageLimit(20);
realm = Realm.getDefaultInstance();
bundle = getIntent().getExtras();
if (bundle != null && bundle.getInt("id") > 0) {
texto = RepositoryTexto.getActiveTextoById(realm, bundle.getInt("id"));
bundle = new Bundle();
bundle.putInt("id", texto.getId());
bundle.putString("titulo", texto.getTitulo());
leiAberta = new LeiAberta();
leiAberta.setArguments(bundle);
adapter.addPage(leiAberta);
}
在第一次运行时,片段上的视图运行良好,当我旋转时,它变为空
有没有办法保持相同的viewpager,适配器和片段而不重新创建它?我已经有onSaveInstance并恢复但无关紧要,因为getActivity在片段上也变为空