Create custom back button in android

I have an application in which there is a menu, and depending on which button you click on the menu, a new action opens. I want every screen to have a back button that will take you to the previous screen, so I'm wondering how do I do this?

Here is the code I 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 a good programming practice for me to put this code in all my actions. How do I create some kind of stack that saves all pages viewed and uses them to return to the previous page?

I need to put the return button in my application so that I cannot use the existing one in the ActionBar.

+5
source share
4

?

ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
    actionBar.setTitle(getResources().getString(R.string.app_name));
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setIcon(R.drawable.app_icon);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
+8

baseClass, Activity.

    @Override
    public void onClick(View v) {
         super.onBackPressed(); // or super.finish();
    }

.

   android:onClick="onClick"

xml- xml. , <include/>

+7

. Android . .

, . , , .

You create a stand in your activity and implement the functionality, as you did above. However, the user can use the equipment return button for the same functionality. This way you will provide the same functionality that is redundant.

+5
source

All Android devices have a hardware return button, and it does exactly what your code lines do, unless overridden to do something else.

You can also find this answer .

+1
source

All Articles