I have an application that has a menu and depending on what button you press in the menu a new activity is opened. I want to have a back button on every screen that will bring you to the previous screen so I'm wondering how do I go about this?
Here is some code I have used that works:
backButton = (ImageButton) findViewById(R.id.back_button);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
However its not good programming practice for me to put this code in all my activities. How do I go about creating some kind of stack that saves all the pages viewed and using that to return to the previous page?
I have to put a back button in my application so I cannot use the existing one in the ActionBar.
Tap the Settings icon to launch the Settings app. Scroll down and tap on Accessibility. Scroll down to the Interaction Controls section and tap System navigation. Tap the button next to 3-button navigation to switch back to the classic 3-button system, or tap the button next to Gesture navigation to enable it.
Back navigation is how users move backward through the history of screens they previously visited. All Android devices provide a Back button for this type of navigation, so you should not add a Back button to your app's UI.
The hardware back button is found on most Android devices. In native applications it can be used to close modals, navigate to the previous view, exit an app, and more.
just an Idea
Create a baseClass which extends Activity. In there declare
@Override
public void onClick(View v) {
super.onBackPressed(); // or super.finish();
}
In all activity extend this Base Class. And in every layout in the button put
android:onClick="onClick"
And to make the xml design of button reusable create it in a separate xml. and add it using <include/>
Have you tried using action bar in your activity ? use in every activity
ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.setTitle(getResources().getString(R.string.app_name));
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setIcon(R.drawable.app_icon);
}
and handle in
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With