简体   繁体   中英

Fragment was unable to replace with fragment in viewpager

I'm working with fragments with ViewPager concept. I'm creating a diary app in which I'm using only one fragment which gets all updates from database and show in it. Until this everything is fine...According to my requirement when i click on a button in fragment i need to show another fragment which allows the user to store the images. My problem is.....

--If i use replace method in fragments it was not replacing properly in the sense if A is fragment which consists of viewpager and B is a fragment i want to replace.
--Then if i use replace B is visible but A also appears under the fragment B

FragmentManager m=getActivity().getSupportFragmentManager();
                FragmentTransaction ft = getActivity().getSupportFragmentManager()
                        .beginTransaction();
                Demobutton demobutton = new Demobutton();

                ft.replace(R.id.lay, demobutton);
                ft.commit();

Hope you guys understand my problem. If you feel my question is incomplete please let me know that.

I have two suggestions depending on how you use the DemoButton Fragment:

1) Maybe your issue is with nested fragments. You get the FragmentManager from the activity but if the Demobutton is already part of an fragment use getChildFragmentManager() of the outer fragment instead.

2) From my experience when using a ViewPager with Fragments the PagerAdapter of the ViewPager should do all the fragment transactions. You could extend and overwrite the class FragmentPagerAdapter from the support library in order to get the correct fragment in your ViewPager when you need it.

I've developed a small example app that achieves this without overwriting native classes.

The point is to use a fragment as a container.

In your ViewPagerAdapter:

@Override
public Fragment getItem(int position) {
    /*
     * IMPORTANT: This is the point. We create a RootFragment acting as
     * a container for other fragments
     */
    if (position == 0)
        return new RootFragment();
    else
        return new StaticFragment();
}

RootFragment layout should look like:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/root_frame" >
</FrameLayout>

You could review my complete explanation here: https://stackoverflow.com/a/21453571/1631136

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM