-1

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.

Android_Noob
  • 487
  • 2
  • 6
  • 19

2 Answers2

1

U have to override onBackPressed() function in your activity and again u have to setContentView to activity_main.xml and remove the super.onBackPressed from onBackPressed.

Something like this:

@Override
public void onBackPressed() {
    //validation if you are in second layout
    if(layout2){
       //do things
        showLayout1();
    }else{
       super.onBackPressed();
    }
}
rafaelasguerra
  • 2,685
  • 5
  • 24
  • 56
Rider
  • 463
  • 1
  • 9
  • 19
0

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.

Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274