Search code examples
androidandroid-fragmentsfragmentmanager

how to switch from one fragment to another fragment android


Hi I have 5 fragments Now first time when I go to Activity of that fragments then default First fragment is called,then on first Fragment there is a button by clicking that button I go to the second fragment,similarly in Second fragment There is a button and clicking that button I go to the third fragment and so on.

Now My Question is that Current I am on Fifth fragment ,Now I want to go fifth fragment to second fragment,what should I do for this? Can any one please tell me?


Solution

  • You can pop the fragment by name. While adding fragments to the back stack, just give them a name.

    fragmentTransaction.addToBackStack("frag2");
    

    Then in fragment5, pop the back stack using the name ie.. frag2 and include POP_BACK_STACK_INCLUSIVE

        someButton.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
    
                FragmentManager fm = getActivity()
                        .getSupportFragmentManager();
                fm.popBackStack ("frag2", FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
        });