Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger back-button functionality on button click in Android

Tags:

android

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?

like image 230
Sourabh Avatar asked Jan 10 '11 17:01

Sourabh


People also ask

What happens when back button is pressed in Android?

However, when the back button is pressed, the activity is destroyed, meaning, the temporary data is lost during this call. This is what the official documentation states. But we do not want to lose this data. To retain the data, we need to override the back pressed method.

How can I tell if my Android back button is pressed?

In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so.


2 Answers

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.

like image 136
sahhhm Avatar answered Oct 13 '22 18:10

sahhhm


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.

like image 20
ekawas Avatar answered Oct 13 '22 18:10

ekawas