开发者

Maintaining view state after switching views?

开发者 https://www.devze.com 2023-04-12 14:48 出处:网络
I have an a开发者_StackOverflow社区ndroid app which has 2 views, and it occasionally switches between them using setContentView(R.layout.viewname);

I have an a开发者_StackOverflow社区ndroid app which has 2 views, and it occasionally switches between them using setContentView(R.layout.viewname);

However when I switch back to a previous view, it appears to have lost all state from when I left it. I.e. EditTexts forget their contents, Buttons forget if they are enabled or disabled etc.

What can I do to prevent this?


This is not the recommended way of switching between two 'views' in Android.

Typically, you call setContentView() only once in Activity.onCreate(), specifying a layout that contains all of the Views you wish to work with (you can of course add more Views to any ViewGroups in your layout, at a later time). To quote the docs for Activity:

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.

You can solve this problem in multiple ways, depending on your specific app requirements, and on what you mean by a 'view'. Here are a few:

  1. Put your views inside separate layouts and have them be the content view of two separate Activities. The data in the fields will save themselves by default, when you switch back to a previous view (does not work going forward!).

  2. Put all your views inside one layout of a single Activity. Use View.setVisibility(...) to toggle the showing and hiding of views you wish to be on screen. Views which are hidden will keep their state.

  3. Use a Fragment for each group of views (you will need the Android compatibility library if you are targeting an app for pre-Honeycomb / 3.0). You can add or remove a Fragment by starting a FragmentTransaction with the FragmentManager. Fragments which are removed still keep their state, and will restore correctly once added again.

If you have a custom View, you can make sure it keeps its state by implementing View.onSaveInstanceState() and View.onRestoreInstanceState(). The answer provided by Qberticus is an excellent reference for this.


Save your view to a field, then load the variable. So if your first contentview is a framelayout, save it

FrameLayout layout1; //activity variable, save the first view to it

then when you load it again, rather than loading it from the xml, load it from the variable: setContentview(layout1);

This should save state, as long as the activity isn't purged in the meantime obviously.

0

精彩评论

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

关注公众号