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:
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!).
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.
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.