onSaveInstanceState () and onRestoreInstanceState ()

前端 未结 13 2332
孤城傲影
孤城傲影 2020-11-22 04:48

I\'m trying to save and restore the state of an Activity using the methods onSaveInstanceState() and onRestoreInstanceState().

13条回答
  •  自闭症患者
    2020-11-22 05:29

    As a workaround, you could store a bundle with the data you want to maintain in the Intent you use to start activity A.

    Intent intent = new Intent(this, ActivityA.class);
    intent.putExtra("bundle", theBundledData);
    startActivity(intent);
    

    Activity A would have to pass this back to Activity B. You would retrieve the intent in Activity B's onCreate method.

    Intent intent = getIntent();
    Bundle intentBundle;
    if (intent != null)
        intentBundle = intent.getBundleExtra("bundle");
    // Do something with the data.
    

    Another idea is to create a repository class to store activity state and have each of your activities reference that class (possible using a singleton structure.) Though, doing so is probably more trouble than it's worth.

提交回复
热议问题