ITKeyword,专注技术干货聚合推荐

注册 | 登录

解决android - ViewPager with Nested Fragments?

itPublisher 分享于

2021腾讯云限时秒杀,爆款1核2G云服务器298元/3年!(领取2860元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1062

2021阿里云最低价产品入口+领取代金券(老用户3折起),
入口地址https://www.aliyun.com/minisite/goods

推荐:Android-ViewPager(FragmentPagerAdapter 和 FragmentStatePagerAdapter)

1.回顾    上篇 使用了 PagerAdapter实现 ViewPager  2.重点    (1)FragmentPagerAdapter  实现 ViewPager    (2)FragmentStatePagerAdapter 实现 ViewPager

My problem

According to the Google's docs:

You can now embed fragments inside fragments. This is useful for a variety of situations in which you want to place dynamic and re-usable UI components into a UI component that is itself dynamic and re-usable. For example, if you use ViewPager to create fragments that swipe left and right and consume a majority of the screen space, you can now insert fragments into each fragment page. To nest a fragment, simply call getChildFragmentManager() on the Fragment in which you want to add a fragment. This returns a FragmentManager that you can use like you normally do from the top-level activity to create fragment transactions. For example, here’s some code that adds a fragment from within an existing Fragment class:

Fragment videoFragment = new VideoPlayerFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.video_fragment, videoFragment).commit();

So I created my own PageFragment. And my PageFragmentAdapterconsist of 3 pages of PageFragment. I also have six fragments: Fragment1, Fragment2, Fragment3, FragmentA, FragmentB, FragmentC. In my MainActivity I initialize my six fragments, my ViewPager and its PageFragmentAdapter (which initialize three PageFragment for itself).

Then I use this method to attach my Fragment1, Fragment2, Fragment3 to each page (to each PageFragment) of PageFragmentAdapter:

PageFragmentAdapter tPageFragmentAdapter = new PageFragmentAdapter(getSupportFragmentManager());
tPageFragmentAdapter.setFirstPage(tFragment1);
tPageFragmentAdapter.setSecondPage(tFragment2);
tPageFragmentAdapter.setThirdPage(tFragment3);

I can recive (via methods in PageFragmentAdapter) Fragments and make "nested fragment" into my PageFragment (of course in onCreate()) like:

getChildFragmentManager().beginTransaction()
.add(R.id.framelayout_history, mFragment)
.addToBackStack(null)
.commit();

Note: I use PageFragment.setNestedFragment() to set mFragment in it.

And it works great! It will help me (but this story is not about it) to simply replace fragments in ViewPager like:

tPageFragmentAdapter.replaceFirstPage(tFragmentA);

But I have one huge problem. Again Google's docs:

Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page. This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state.

As you can see PageFragmentAdapter can destroy each my PageFragment and of course its nested fragment. And when it will be recreated it will have a NULL instead mFragment value. I am trying to save it via getChildFragmentManager().putFragment() and then get it by getChildFragmentManager().getFragment(). But it doesn't worked.

推荐:android viewpager

viewpager 是一个好用,又华丽丽的控件。 1. 禁止viewpager 左右滑动,但不影响viewpager 每个paer上的事件 public class MainView extends ViewPager{ privat

Question

So my question is: How to save my nested fragment in my parent fragment? Is it possible?

I would greatly appreciate for your help. Alex. P.S. Really sorry for my English:)

EDIT

Thx @AndroidBegin.com for the answer!

This seems to be a bug in the newly added support for nested fragments. Basically, the child FragmentManager ends up with a broken internal state when it is detached from the activity. A short-term workaround that fixed it for me is to add the following to onDetach() of every Fragment which you call getChildFragmentManager() on:

@Override
public void onDetach() {
    super.onDetach();

    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);

    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
android android-fragments nested android-viewpager fragmentpageradapter
edited Sep 28 '13 at 9:57 asked Sep 24 '13 at 9:37 AlexMomotov 1,829 5 14 29      Help me! Share your idea! –  AlexMomotov Sep 24 '13 at 13:27

 | 

1 Answers
1

解决方法

Try this on your fragment.

public class Fragment2 extends SherlockFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.viewpager_main, container, false);
        // Locate the ViewPager in viewpager_main.xml
        ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
        // Set the ViewPagerAdapter into ViewPager
        mViewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager()));
        return view;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class
                    .getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}

Source : http://www.androidbegin.com/tutorial/actionbarsherlock-side-menu-navigation-nested-viewpager-fragment-tabs-tutorial/


answered Sep 24 '13 at 15:50 AndroidBegin.com 354 2 10      OK. And how to get FragmentManager from Field? –  AlexMomotov Sep 27 '13 at 10:54      I still waiting correct answer :\ –  AlexMomotov Sep 28 '13 at 9:17      Check out this question for more info stackoverflow.com/a/15656428/2397414 –  AndroidBegin.com Sep 28 '13 at 9:33      wow! Thank you very much! –  AlexMomotov Sep 28 '13 at 9:54

 | 

推荐:Android中ViewPager使用FragmentPagerAdapter(底部圆点)

     上一篇 http://blog.csdn.net/tibib/article/details/8753769简单的介绍了下ViewPager的使用,上一次使用的是PagerAdapter来生成适配每一页,但最常用的是


相关阅读排行


相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱

如果您没有收到激活邮件,请注意检查垃圾箱。