Trigger back-button functionality on button click in Android
I k开发者_Python百科now 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?
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.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// your code here
return false;
}
return super.onKeyDown(keyCode, event);
}
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:
- Android - Return to calling Activity
- Android: Go back to previous activity
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.
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();
}
});
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.
精彩评论