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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With