7

I create sample app to show some data to user when user start specific activity and click on specific button the app start new fragment (only fragment added to activity for now ) my problem is when user click back the fragment and the activity removed and go to parent activity. using this code to do that

android.support.v4.app.FragmentManager fragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
fragmentManager.popBackStack();

also I use the same code in another action when user click in specific button fragment and back correctly.
Can anyone help me to solve that

Yaseen Ahmad
  • 1,807
  • 5
  • 25
  • 43
Azak
  • 270
  • 1
  • 5
  • 15

4 Answers4

14

Add fragments to back stack when create them and override onBackPressed in your activity.

To add fragment

FragmentManager mFragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.addToBackStack("tag of fragment");
ft.add("your container id", fragment);
ft.commit();

onBackPress

@Override
public void onBackPressed() {
    if (mFragmentManager.getBackStackEntryCount() > 0)
       mFragmentManager.popBackStackImmediate();
    else super.onBackPressed();
}
faranjit
  • 1,567
  • 1
  • 15
  • 22
3

To remove only fragment you have to add that fragment in addToBackStack(TAG) so that when you press back it popout only Fragment which are added to stack

Burhanuddin Rashid
  • 5,260
  • 6
  • 34
  • 51
2

override onBackPressed() and remove fragment. Back stack for fragments works differently as it stores transaction not fragments. So can not pop back a fragment but a transaction

Ramit
  • 416
  • 3
  • 8
1

This is work for me to handle backpressin a fragment in a fragment to remove backstack.

@Override
public void onResume() {
    super.onResume();

    if (getView() == null) {
        return;
    }

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {

            if (keyEvent.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {

                Toast.makeText(getActivity(), "Clicked Back", Toast.LENGTH_SHORT).show();
                getActivity().finish();
                return true;
            }
            return false;
        }
    });
}