Creating custom back button in android

北城以北 提交于 2019-12-06 03:26:18

问题


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.


回答1:


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




回答2:


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);
    }
}



回答3:


I would suggest against having a custom back button. Android has a hardware back button. Pressing the haradware back button will navigate to the previous.

I don't think you need a custom back button. I don't think its a good programming practice to override the default behaviour.

You create a backbutton in your activity and implementing the functionality as you have done above. Still the user can use the hardware back button for the same functionality. So you would be providing the same functionality which is redundant.




回答4:


There is a hardware back button on all android devices, and it does exactly what your lines of codes do, unless overridden to do something else.

You can refer to this answer as well.



来源:https://stackoverflow.com/questions/16103225/creating-custom-back-button-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!