场景:Activity A打开Activity B,Activity B在viewpager中使用FragmentPagerAdapter有两个fragment a和b,fragment a和b有一些单选按钮和复选框供用户交互;
即使我将活动 B 留给 A,我也需要将按钮和复选框状态存储在片段中
我的尝试:1-删除了 super.onBack() 以强制系统在活动中调用 onSavedInstanceState,但仍然无法将片段保存到它,因为我在适配器中实例化它们并且不知道如何创建相同的对象他们的活动
2-在每个片段中尝试了 onSaveInstanceState()、onViewStateRestored(),并且从未在 oncreate() 中使用 setRetainInstance(true) 调用 onSavedInstance;然后通过调用 onPause() 来强制调用 onSaveInstanceState()
我阅读了堆栈上的大多数可用解决方案,但没有一个有效,我的代码如下;
public class FilterPagerAdapter extends FragmentPagerAdapter {
public final static int KEYWORDS_TAB = 0;
public final static int AREAS_TAB = 1;
private int tabCount;
private Context context;
public FilterPagerAdapter(FragmentManager fm, int tabCount, Context context) {
super(fm);
this.tabCount = tabCount;
this.context = context;
}
@Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case KEYWORDS_TAB:
fragment = KeyWordsFragment.newInstance();
break;
case AREAS_TAB:
fragment = AreasFragment.newInstance();
break;
default:
return null;
}
return fragment;
}
@Override
public int getCount() {
return tabCount;
}
@Override
public CharSequence getPageTitle(int position) {
String tabTitle = "";
switch (position) {
case KEYWORDS_TAB:
tabTitle = context.getResources().getString(R.string.tab_keywords);
break;
case AREAS_TAB:
tabTitle = context.getResources().getString(R.string.tab_area);
break;
default:
}
return tabTitle;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filters);
ButterKnife.bind(this);
mAreas = new Areas();
mKeywords = new KeyWords();
viewControllers();
}
private void viewControllers() {
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_keywords), CATEGORIES_TAB);
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_area), BRANDS_TAB);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.addOnTabSelectedListener(this);
filterPagerAdapter = new FilterPagerAdapter(getSupportFragmentManager(),
tabLayout.getTabCount(), this);
viewPager.setAdapter(filterPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
@Override
public void onBackPressed() {
startActivity(new Intent(FiltersActivity.this, BranchesActivity.class));
}
@Override
public void onStop() {
super.onStop();
tabLayout.removeOnTabSelectedListener(this);
}
}