what does onBackPress call in a Fragment

时光毁灭记忆、已成空白 提交于 2019-12-24 11:07:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!