Redo.ZeveN Redo.ZeveN - 6 months ago 47
Java Question

Switching layout whit onBackPressed()

I'm in trouble. I want to switch between layouts using the physical back button. I found this:

@Override
public void onBackPressed() {
RelativeLayout layout2 = (RelativeLayout)findViewById(R.id.layout2);// check if layout2 is open
if(layout2.getVisibility() == View.VISIBLE){
setContentView(R.layout.main);
return;
}else{
super.onBackPressed();
}

}


Is the checking part correct?

Answer

Make RelativeLayout decalre globally so you can access in OnBack() method

 RelativeLayout layout2

this line you have to put in the OnCreate() method

 layout2 = (RelativeLayout)findViewById(R.id.layout2);// 

and finally check visibility of layout

@Override
public void onBackPressed() {
if(layout2.getVisibility() == View.VISIBLE){
    setContentView(R.layout.main);
    return;
}else{
    super.onBackPressed(); 
    }

}

enjoy coding............