I have a single activity which has two buttons on it .each button opens a new layout .now if i will press back my application will close .but i want to return on Mainactivity and if the user presses back again then app is closed and if he does not press and goes to the second layout and press back then app should not get closed. the condition should be if the user is on Mainactivity and he presses back button then the application closes. I came up with an idea on onBackPress method if i could set this condition
if (k==1 && Its not a Mainactivity(or the user is not inside a Mainactivity)) {//I dont know how to check for that
Intent i = new Intent(this,Mainactivity.class);
startActivity(i);
this.finish();
} else if (k==1 && Its a Mainactivity(or the user is inside a Mainactivity)) {
this.finish(); //then i just want to close the application,I dont know this.finish() ,It does not close the app but still it runs in background
}
If u guys want to see my code here it is a simple example of what i am trying to achieve:-
public class MainActivity extends AppCompatActivity {
Button btn1,button2; //Creating button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1= (Button)findViewById(R.id.btn1); //finding button1
button2=(Button)findViewById(R.id.button2); //finding button2
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setContentView(R.layout.btn1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setContentView(R.layout.btn2);
}
});
}
}
Please help me.