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