Reputation: 77
I am trying to create a back button to return to the previous screen. I have a next button which moves from the current screen (screen2) to the next screen (screen4) however I want a back button to do the reverse process .. i.e to return to screen 2. I have called the button and named the id. I was wondering could anyone tell me why the code below isn't working.. The code is as follows:
Button backbutton;
backbutton = (Button) findViewById(R.id.back_button);
backbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setContentView(R.layout.screen2);
}
});
`
Upvotes: 1
Views: 663
Reputation: 5053
Call this method onBackPressed();
when you are click button.
backbutton = (Button) findViewById(R.id.back_button);
backbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});`
Upvotes: 0
Reputation: 123
If you are trying to make this button act the same as the regular back button on the Android device itself you can make use of the onBackPressed() method
So your code would be something like this:
backbutton = (Button) findViewById(R.id.back_button);
backbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed(); //OPTION 1: If in an activity
getActivity().onBackPressed(); //OPTION 2: If in a fragment
}
});
Choose whichever line of code suits your needs depending on where you are, in activity vs in fragment.
Upvotes: 3
Reputation: 2164
You can simple call the onBackPressed()
system method inside your onClickListener
interface.
something like this:
backbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
Upvotes: 0
Reputation: 2730
Just finish activity
backbutton = (Button) findViewById(R.id.back_button);
backbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
Upvotes: 0