Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom back button in android

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.

like image 293
DMC Avatar asked Apr 19 '13 11:04

DMC


People also ask

Can I change the back button in Android?

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.

Does Android have a back button?

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.

What is the Back button called in Android?

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.


2 Answers

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/>

like image 174
stinepike Avatar answered Sep 20 '22 16:09

stinepike


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);
    }
}
like image 36
Rahul Patil Avatar answered Sep 21 '22 16:09

Rahul Patil