Trigger back-button functionality on button click in Android
AndroidAndroid Problem Overview
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?
Android Solutions
Solution 1 - Android
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.
Solution 2 - Android
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.
Solution 3 - Android
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// your code here
return false;
}
return super.onKeyDown(keyCode, event);
}
Solution 4 - Android
layout.xml
<Button
android:id="@+id/buttonBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="finishActivity"
android:text="Back" />
Activity.java
public void finishActivity(View v){
finish();
}
Related:
Solution 5 - Android
If you are inside the fragment then you write the following line of code inside your on click listener,
getActivity().onBackPressed();
this works perfectly for me.
Solution 6 - Android
With this code i solved my problem.For back button paste these two line code.Hope this will help you.
Only paste this code on button click
super.onBackPressed();
Example:-
Button backButton = (Button)this.findViewById(R.id.back);
backButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
super.onBackPressed();
}
});
Solution 7 - Android
Well the answer from @sahhhm didn't work for me, what i needed was to trigger the backKey from a custom button so what I did was I simply called,
backAction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyRides.super.onBackPressed();
}
});
and it work like charm. Hope it will help others too.