【问题标题】:How to use onSaveInstanceState() for Fragments如何对片段使用 onSaveInstanceState()
【发布时间】:2014-09-10 02:53:33
【问题描述】:

当我的 Fragment 被销毁时,我需要保存一些成员变量。但是,研究表明片段变量没有像活动一样保存onSaveInstanceState。因此,我无法保存这些变量。

我的片段是 PageViewer 的一部分,所以我不知道如何store the Fragments in the Bundle of the Activity's onSaveInstanceState(我没有明确定义片段,因为它们是在 PageViewer 适配器中创建的!)

我看到它建议我使用 Fragment Arguments 来存储这些变量,但是当我在我的 Arguments 包上调用 containsKey 时,我总是得到 false

当 Fragments 的 onStop 被调用时,您对保存 Fragments 的成员变量有何建议?

这是我的 Fragment 的onCreateView

public FinalCalcFragment(){
        setArguments(new Bundle());
    }    
@Override
    public View onCreateView(LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(
                R.layout.activity_grade_calculator, container, false);
        Bundle args = getArguments();
        if(args.containsKey("visYes")){
            firstLoad = args.getBoolean(PERSISTENT_FIRSTLOAD_BUNDLE_KEY);
            System.out.println("contains the key");
        }
        context = this.getActivity();

        if(firstLoad) {   //This is so that I don't reset my views when recreating.
            bindAll();
            setInitialViews();  
            setListeners();
        }
        firstLoad = false;
        return rootView;
    }

这是我的onPauseonSaveInstanceState。我尝试将我的论点存储在两者中,但都没有奏效。

@Override
public void onPause(){
    super.onPause();
    getArguments().putBoolean(PERSISTENT_FIRSTLOAD_BUNDLE_KEY, firstLoad);
    getArguments().putBoolean("visYes", ((TextView) rootView.findViewById(R.id.tv_grade_calc_result)).isShown());
}

@Override
public void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);
    getArguments().putBoolean(PERSISTENT_FIRSTLOAD_BUNDLE_KEY, firstLoad);
    getArguments().putBoolean("visYes", ((TextView) rootView.findViewById(R.id.tv_grade_calc_result)).isShown());
}

这是我的适配器getItem 方法的摘录。

@Override
public Fragment getItem(int i) {
    //System.out.println("We are trying to get item " + i);
    switch(i) {
        case 0:
            Fragment fragment = new FinalCalcFragment();
            return fragment;

【问题讨论】:

    标签: android android-activity android-fragments android-fragmentactivity android-lifecycle


    【解决方案1】:

    您应该使用 Bundle outState 来保存片段实例状态,就像使用活动一样。更改 getArguments() 返回的参数无效。 然后在onCreateView 中首先检查是否通过了saveInstanceState。如果 savedInstanceState 不为 null 则使用它,如果为 null 则使用 getArguments() 返回的 Bundle。

    【讨论】:

      猜你喜欢
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多