androidmultiple-viewssetcontentview

How to use setContentView(layout_id) second time in main_activity of android code?


My activity_main.xml has 2 buttons. I have implemented onClickListner(); for both of them .

For MainActivity, - > setContentView(R.layout.activity_main) This activity_main has the 2 buttons.

Button1 - setContentView(R.layout.layout1); Button2 - setContentView (R.layout.layout2);

Is this the proper way to use?? Because..

The program runs fine. The problem is that when I click Button2, the layout2 loads, I want to come back to main_activity now, So I press 'Back' button. The entire app closes..!! I am taken to homescreen of the phone.

How to get around this?? I say ViewSwitcher. I do not have a button to come back.

Any other way?? Please excuse for basic question and bad English.


Solution

  • You should pretty much never call setContentView() more than once. What you're describing is standard backstack behavior. Either start a new Activity whatever layout you're transitioning to, or switch to using Fragments, and add a new Fragment to the backstack instead of calling setContentView().

    Both approaches will give you native behavioral support for the back button.