Activity 通过 Fragment保存大块数据的一种方法。摘自android开发官网

 
 

http://developer.android.com/guide/topics/resources/runtime-changes.html


Retaining an Object During a Configuration Change

If restarting your activity requires that you recover large sets of data, re-establish a network connection, or perform other intensive operations, then a full restart due to a configuration change might be a slow user experience. Also, it might not be possible for you to completely restore your activity state with the Bundle that the system saves for you with the onSaveInstanceState() callback—it is not designed to carry large objects (such as bitmaps) and the data within it must be serialized then deserialized, which can consume a lot of memory and make the configuration change slow. In such a situation, you can alleviate the burden of reinitializing your activity by retaining a Fragment when your activity is restarted due to a configuration change. This fragment can contain references to stateful objects that you want to retain.

When the Android system shuts down your activity due to a configuration change, the fragments of your activity that you have marked to retain are not destroyed. You can add such fragments to your activity to preserve stateful objects.

To retain stateful objects in a fragment during a runtime configuration change:

  1. Extend the Fragment class and declare references to your stateful objects.

  2. Call setRetainInstance(boolean) when the fragment is created.

  3. Add the fragment to your activity.

  4. Use FragmentManager to retrieve the fragment when the activity is restarted.

For example, define your fragment as follows:

public class RetainedFragment extends Fragment {

   
// data object we want to retain
   
private MyDataObject data;

   
// this method is only called once for this fragment
   
@Override
   
public void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
       
// retain this fragment
        setRetainInstance
(true);
   
}

   
public void setData(MyDataObject data) {
       
this.data = data;
   
}

   
public MyDataObject getData() {
       
return data;
   
}
}

Caution: While you can store any object, you should never pass an object that is tied to the Activity, such as a Drawable, an Adapter, a View or any other object that's associated with a Context. If you do, it will leak all the views and resources of the original activity instance. (Leaking resources means that your application maintains a hold on them and they cannot be garbage-collected, so lots of memory can be lost.)


你可能感兴趣的:(Activity 通过 Fragment保存大块数据的一种方法。摘自android开发官网)