0

I want to add to my android application back button listener which use popBackStack with unique values. For example, I have fragments 1,2,3,4,5 and i visit them in order 1->2->3->2->3->4->3->5->3.

If I am in fragment 3 at end of queue, back button should back me to fragment 5, in this fragment back button should back me to fragment 4, in this to fragment 2 and in this to fragment 1 (3->5->4->2->1).

I have code, which works, but click on back button return me to previous fragment in this queue (3->5->3->4->3->2->3->2->1).

view.setOnKeyListener((view1, keyCode, keyEvent) -> {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (popDone) {
                popDone = false;
                return true;
            } else {
                if (getActivity().getSupportFragmentManager().getBackStackEntryCount() > 0) {
                    popDone = true;
                    getActivity().getSupportFragmentManager().popBackStack();
                } else {
                    getActivity().finish();
                }
                return true;
            }
        }
        return false;
    });
Jawad Malik
  • 608
  • 5
  • 21
daasz
  • 9
  • 5

2 Answers2

0

It's not problem for your back action, but adding fragment. Read off document about using fragment. I suppose you are adding to backstack every fragment with no sense. Remove this line in your FragmentTransaction, whenever you don't need back stack fragmentTransaction.addToBackStack(null);

GensaGames
  • 5,538
  • 4
  • 24
  • 53
0

Man, adding all fragments into backstack and not reusing it - it's bad practice. When you need to open fragment you can check it in backstack. I do it like this:

private void showFragmentIfNeeded(Fragment fragment) {
    if (fragmentManager.findFragmentByTag(CURRENT_FRAGMENT_TAG) != null)
        fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag(CURRENT_FRAGMENT_TAG)).commit();
    if (fragmentManager.findFragmentByTag(fragment.getClass().getSimpleName()) != null)
        fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag(fragment.getClass().getSimpleName())).commit();
    else
        fragmentManager.beginTransaction().add(R.id.fragment_container, fragment, fragment.getClass().getSimpleName()).commit();
    CURRENT_FRAGMENT_TAG = fragment.getClass().getSimpleName();
}