3

This is my class name

public class PrimaryFragment extends Fragment implements OnRestartRequest {

    @Override
    public void onBackPressed() {
        if (mCardStackLayout.isCardSelected()) {
            mCardStackLayout.restoreCards();
        } else {
            super.onBackPressed();
        }
    }

Error on this line: super.onBackPressed();

I don't know what's the problem in fragment class's on back pressed button.

Sufian
  • 6,405
  • 16
  • 66
  • 120
Hardik Thummar
  • 61
  • 1
  • 1
  • 4

4 Answers4

6

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

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Smit Davda
  • 638
  • 5
  • 15
3

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);

Amarjit
  • 4,327
  • 2
  • 34
  • 51
1

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.

Nir Duan
  • 6,164
  • 4
  • 24
  • 38
0

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;
    }
}
Atiq
  • 14,435
  • 6
  • 54
  • 69