Trigger back-button functionality on button click in Android


Question

I know we have back button in android to move us back on the previous form, but my team leader asked to put a back button functionality on button click

How can I do this?

1
48
8/26/2013 10:31:45 AM

Accepted Answer

You should use finish() when the user clicks on the button in order to go to the previous activity.

Button backButton = (Button)this.findViewById(R.id.back);
backButton.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    finish();
  }
});

Alternatively, if you really need to, you can try to trigger your own back key press:

this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));

Execute both of these.

120
4/28/2015 2:26:01 PM

If you need the exact functionality of the back button in your custom button, why not just call yourActivity.onBackPressed() that way if you override the functionality of the backbutton your custom button will behave the same.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon