开发者

Android: Saving contents of a listview onSaveInstanceState

开发者 https://www.devze.com 2023-03-05 21:14 出处:网络
Is there an built in way to save the contents 开发者_运维技巧of a listView as part of onSaveInstanceState to then restore later?I want the listView to look the same if the user hit the back button and

Is there an built in way to save the contents 开发者_运维技巧of a listView as part of onSaveInstanceState to then restore later? I want the listView to look the same if the user hit the back button and now onCreate is being called again.


If you set your activity's launchMode to singleTask, then (unless the application was terminated / gc called upon) your data (list) will be preserved.

This way your device will hold only one running instance of your application at a time, so when you "launch it again" no matter from where, if it's already running in the background, then that instance will show up (with the latest data).

If there is a risk that your application was finished, and you still need the latest list of data to show up, this solution won't work.
But you could give a try to SharedPreferences: save the current data to the application's SharedPreferences, and restore it from there when launching it.

If it's ok, to have the predefined new list on each clean start of the application, but when getting it into foreground, you need the last seen items in your list, you should use the savedInstanceState parameter of your onCreate method:

private static final String MYLISTKEY = "myListLabels";
private ArrayList<String> listLabels = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    if (savedInstanceState.containsKey(MYLISTKEY))
    {
        listLabels = savedInstanceState.getStringArrayList(MYLISTKEY);
    }
    else
    {
        // TODO: populate explicitely your list
    }
}

@Override
protected void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
    outState.putStringArrayList(MYLISTKEY, listLabels);
}

where listLabels contains the labels for your list.
It's not necessary for them to be of type String, you can put any type inside your Bundle.


When the user hits the back button the activity is always destroyed, so there will not be any restoring from savedinstance.

Android Training

When your activity is destroyed because the user presses Back or the activity finishes itself, the system's concept of that Activity instance is gone forever because the behavior indicates the activity is no longer needed.

0

精彩评论

暂无评论...
验证码 换一张
取 消