Search code examples
androidandroid-fragmentsandroid-viewpager

How to open another fragment from inside a ViewPager fragment?


I followed this tutorial to build an app with three fragments in sliding view (ViewPager).

https://c1ctech.com/android-viewpager-example-to-create-sliding-screens/

The app was built successfully. Then I added a button inside FragmentOne. And also created another fragment named FragmentFour with fragment_four.xml layout file.

Now I want to link the FragmentFour with FragmentOne through onClickListener with the button I created before. When in FragmentOne the button will be clicked, and it'll launch FragmentFour. To achive that, inside onClickListener I added these codes-

FragmentFour fragFour = new FragmentFour();
                    FragmentManager fragmentManager = getChildFragmentManager();
                    FragmentTransaction transaction = fragmentManager.beginTransaction();
                    transaction.replace(R.id.main_frameLayout, fragFour);
                    transaction.addToBackStack(null);
                    transaction.commit();

But after running the app, when I click on that button from inside the FragmentOne, FragmentFour's layout overlaps over the FragmentOne's layout. And FragmentTwo and FragmentThree can be accessible via sliding from FragmentFour, but I don't want this.

If anything wrong here, please help me.


Solution

  • The problem is now gone. I just need to make few changes to my codes. Inside onClickListener, I changed my codes like this-

    Before:

    FragmentManager fragmentManager = getChildFragmentManager();
    

    After:

    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
    

    And inside the fragment_four.xml file's relative layout:

    android:background="@color/bgcolor"
    android:clickable="true"
    android:focusable="true"