0

I have Fragments (A, B, C) in Navigation Drawer Activity and subfragments (A2, A3, B2, B3) respectively to Fragments A and B. I need them to work like this: 1) A -> B -> C -> B. when I press the back button, then I need to return A. That is, Fragment A is the main 2) A-> A2-> A3 When I press the back button then I need to return A2, then A. I tried to use addToBackStack(), it helps on the second example, but not the first example. So,help me guys,thanks a lot))) (Sorry for my not understandable English)

Mukhit
  • 152
  • 2
  • 10

2 Answers2

1

Step 1. Make One Interface Like this

public interface HostInterface {
        void changeCurrentFragmentTo(int currentFragmentId, Bundle bundle);
    }

   implement it in your Main Activity.

Step 2. In your fragment

    private HostInterface hostInterface;

        @Override
            public void onAttach(Context context) {
                super.onAttach(context);
                hostInterface = (HostInterface) context;
            }

        @Override
            public void onActivityCreated(@Nullable Bundle savedInstanceState) {
                super.onActivityCreated(savedInstanceState);

                if (getView() != null) {
                    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_DOWN) {
                                if (keyCode == KeyEvent.KEYCODE_BACK) {
                                    **hostInterface.changeCurrentFragmentTo(yorfragment,null);**
                                    return true;
                                }
                            }
                            return false;
                        }
                    });
                }
            }

Step 3. Now you got call back in Activity. Call New Fragment as per your Requirement

VIISHRUT MAVANII
  • 11,410
  • 7
  • 34
  • 49
0

You could use the FragmentManager you directly address the fragment you want to show or hide.

var newFragmentTag = typeof(NewFragment).Name;
var newFragment = FragmentManager.FindFragmentByTag(newFragmentTag);
if(newFragment != null)
{
    FragmentManager.BeginTransaction().Hide(currentFragment).Show(newFragment).Commit();
}
else
{
    // new Instance of newFragment and hide/show ...
}
Aiko West
  • 791
  • 1
  • 10
  • 30