Search code examples
androidback-buttonandroid-button

Setup a button to act as back button


I would like to setup a simple Alert View's OK button to act as the back button acts. What method should I use?

AlertDialog.Builder alt_bld = new AlertDialog.Builder(this.getContext());
                AlertDialog alert = alt_bld.create();
                alert.setTitle("Your score is: " + score);
                alert.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { 
  //here would be the "back button's method"
}});
                alert.show();   

Solution

  • You have to call the finish method in order to destroy activity.

    AlertDialog.Builder alt_bld = new AlertDialog.Builder(this.getContext());
                    AlertDialog alert = alt_bld.create();
                    alert.setTitle("Your score is: " + score);
                    alert.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) { 
    
                       // Enter you activity Name add call finish.
    
                       MyAcitivity.this.finish(); // Or MyAcitivity.this.onBackPressed()
    
    }});
    alert.show();