开发者

Saving advanced state of an Android Listview

I know that Android provides a mechanism to allow developers to save and restore states in an Activity via the following methods:

protected void onSaveInstanceState (Bundle outState)
protected void onRestoreInstanceState (Bundle savedInstanceState)

I've seen numerous examples whereby people show how to save simple state (such as the current index in a listview), and many examples where people say that the listview should just be backed by a data model which will allow the list to be restored. However, when things get more complicated and the user interaction more 开发者_Go百科involved, I've been struggling to find out the correct way to save this state.

I have a listview which contains custom controls for each row. When clicked a row will expand with animation to show additional details to the user... within the additional details view, the user is also able to change certain things. Now I know that if my Activity is destroyed (or my Fragment replaced), the current state reflecting the UI changes and the user's interaction with the list is now lost.

My question is how do I got about correctly saving this detailed state of my listview such that the state of each custom component row is also preserved?

Thanks!

Edit: Thanks for the replies below. I understand that SharedPreferences can be used to store key-value state, however, I guess I am more interested in the view states.... for instance Android will automatically save/restore the viewstate of an EditText field (i.e. its contents) in my activity , so how do I go about achieving the same thing with more complex custom components in a listview? Do I really have to save this state all manually myself (i.e. save exactly which listview rows have been expanded, save all the ui changes the user has made/toggled, etc.)?


I don't like to say this, but it seems that this must all be done yourself. The framework does not offer a pre-made method for "save state of view".

Whether you save the state in a Bundle or SharedPreferences, I think the point is that you need to determine state variables that reflect your current list choices, persist them yourself, and onResume() you need to reintroduce that state into your activity.

... quite a manual process, as you say ...


I am not sure but I assume SharedPreferences is what you might be looking for.


Make use of SharedPreferences in onPause() method.

where you can store all you activities data when it is moving to background.

When ever you want to restore the data fetch from the Shared Preferences.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜