1

I want to move back to my previous fragment when I click on the back button. What I am doing is not working.

The code for fragment replacement:

Fragment fragment=new MyFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
    .beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in,R.anim.slide_out);
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();

The code for catch hit of Back button:

@Override
public void onResume() {
    super.onResume();
    getActivity().invalidateOptionsMenu();
    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                getActivity().finish();
                getActivity().overridePendingTransition(R.anim.slide_enter, R.anim.slide_exit);
                return true;
            }
            return false;
        }
    });

I have also tried

getActivity().getSupportFragmentManager().popBackStack();
ceph3us
  • 7,326
  • 3
  • 36
  • 43
Shivangi
  • 81
  • 2
  • 13

2 Answers2

0

Change like this this mat help

Fragment fragment=new MyFragment();
               FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
               FragmentTransaction fragmentTransaction = fragmentManager
                        .beginTransaction();
                fragmentTransaction.setCustomAnimations(R.anim.slide_in,R.anim.slide_out);
                fragmentTransaction.replace(R.id.container_body, fragment).addToBackStack(null);
                fragmentTransaction.commit();

Let me know if any error

Manish
  • 234
  • 2
  • 13
0

you can do like below.

   DetailsFragment detailsFragment = new DetailsFragment();
            Bundle bundle = new Bundle();
            bundle.putString("ID", Id);
                    detailsFragment.setArguments(bundle);

            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.add(R.id.detail_container, detailsFragment);
            transaction.addToBackStack(this.getClass().getSimpleName());
            transaction.hide(DetailsFragment.this);
            transaction.commit();
Vishal Thakkar
  • 2,117
  • 2
  • 16
  • 33