Fragment was unable to replace with fragment in viewpager

非 Y 不嫁゛ 提交于 2019-12-13 05:04:25

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/16805678/fragment-was-unable-to-replace-with-fragment-in-viewpager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!