当前位置: 动力学知识库 > 问答 > 编程问答 >

android - How do handle onBackPressed() in Fragment?

问题描述:

This question already has an answer here:

  • How to implement onBackPressed() in Fragments?

    25 answers

网友答案:

There is no onBackPressed() method in Fragment. You can do something like calling getActivity().onBackPressed() from your fragment.

网友答案:

Fragmetns doesn't have their own OnBackPressed and you have to handle their transaction from its parent Actvitiy which contains that fragment.

Example: // in Parent Activity on Fragmetn

@Override
public void onBackPressed() {
    // This will get you total fragment in the backStack
    int count = getFragmentManager().getBackStackEntryCount();
    switch(count){
        case 0:
            super.onBackPressed();
            break;
        case 1:
            // handle back press of fragment one
            break;
        case 2:
            // and so on for fragment 2 etc
            break;
        default:
            getFragmentManager().popBackStack();
            break;
    }
}
网友答案:

You should call getActivity() from inside you fragment like this:

getActivity().onBackedPressed();

Note: watch that you import the right getActivity(), If you use android.support.v4.app.Fragment you need to import the correct package.

网友答案:

Fragment does not have onBackPress() method as we have for activity. I prefer handling back press using below code, Hope it help you:

 private void handleBackPress(View view) {


        view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.setOnKeyListener( new View.OnKeyListener()
        {
            @Override
            public boolean onKey( View v, int keyCode, KeyEvent event )
            {
                if( keyCode == KeyEvent.KEYCODE_BACK )
                {

                    cancelCountDownTimerAndSaveValues();

                    if (Constants.Fragments.CurrentFragment != null)
                    {
                         getActivity().getSupportFragmentManager().popBackStack();

                    }

                    return true;
                }
                return false;
            }
        } );
    }

and here view is your main view for fragment as you get from

View view = inflater.inflate(R.layout.xxxxx, container, false);

分享给朋友:
您可能感兴趣的文章:
随机阅读: