问题
In a Fragment i have this:
onPause(){
super.onPause();
if(flag){
getActivity.finish();
}else{
}
}
onResume(){
flag = true;
super.onResume();
}
and there is a Button, on click i set this flag to false:
Button.onClick{
flag = false;
}
The idea is:
when the button is clicked don't finish this Activity. But when device BackButton is pressed finish().
But this logic isn't working. The reason is, when i press BackButton of the device, onPause is not being called.
This is the 4th Fragment in the Activty. So when i press BackButton i can see the 3rd Fragment. Which i don't want to.
I am using this on a API 10 device, But my application uses support library v4.
Thank You.
回答1:
If you want to close the activity on the back press, then Override the onBackPressed
inside the activity as following:
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("yourfragment");
if (fragment instanceOf YourFragmet) {
finish();
return;
}
super.onBackPressed();
}
If you want to close the activity on the button click, then you can call
Button.onClick{
getActivity().onBackPressed();
}
OR
Button.onClick{
getActivity().finish();
}
If When you are transitioning between Fragments, you call addToBackStack() as part of your FragmentTransaction, then the back button will take you to the fragment on the top of the back stack
回答2:
Why can't you use onDetach() of Fragment? On Back key pressed, there will be onDetach() called on the fragment to remove that.
@Override
public void onDetach() {
super.onDetach();
if(flag){
getActivity.finish();
}else{
}
}
来源:https://stackoverflow.com/questions/13758597/what-does-onbackpress-call-in-a-fragment