FragmentPagerAdapter - 如何处理取向的变迁? [英] FragmentPagerAdapter - How to handle Orientation Changes?

查看:99
本文介绍了FragmentPagerAdapter - 如何处理取向的变迁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用含有需要被通知关于改变到数据库中的几个碎片一个FragmentPagerAdapter。我这样做是通过循环片段,其中实现一个回调接口,并调用refreshData()方法。

I use a FragmentPagerAdapter containing several Fragments that need to be notified about changes to the database. I do this by iterating over the fragments, which implement a callback interface, and calling a refreshData() method.

这只是正常,直到设备改变方向。一个方向变化后,该片段UI并不明显刷新尽管调用的方法似乎工作。

This works just fine until the device changes orientation. After an orientation change, the fragment UI does not visibly refresh even though the method call seems to work.

从我已阅读到目前为止,这是因为FragmentPagerAdapter处理片段生命周期和接收回调的片段并不实际显示的内容。

From what I have read so far this occurs because the FragmentPagerAdapter handles the fragment life-cycle and the fragments that receive the callback are not the ones that are actually displayed.

private class DataPagerAdapter extends FragmentPagerAdapter {

    private DataFragment[] fragments = new DataFragment[] {
                                     new FooDataFragment(), BarDataFragment()};

    public DataPagerAdapter(android.support.v4.app.FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return fragments[position];
    }

    @Override
    public int getCount() {
        return fragments.length;
    }

    public DataFragment[] getFragments() {
        return fragments;
    }
}

protected void refreshData() {
    for (DataFragment dataFragment : mPagerAdapter.getFragments()) {
     dataFragment.refreshData();
}

余临时固定使用每个片段内的广播接收机这一问题,但这种解决方案似乎是浪费,并可能造成内存泄漏。如何解决这个正常吗?我用不同的布局和逻辑在横向模式下,所以我希望的方向变化后,使用新创建的片段。

I temporarily fixed this issue using a broadcast receiver inside each fragment, but this solution seems to be wasteful and might create memory leaks. How to I fix this properly? I use a different layout and logic in landscape mode so I want to use the newly created fragments after an orientation change.

推荐答案

是像你说的FragmentManager处理不叫的方向变化,从而的getItem 适配器后的碎片。但是你可以重写方法 instantiateItem()这就是所谓的,即使方向改变后投对象,以片段并将其保存在您的数组。

Yes like you said FragmentManager handles fragments after orientation change so getItem in adapter is not called. But you can override method instantiateItem() which is called even after orientation change and cast Object to Fragment and save it in your array.

 @Override
 public Object instantiateItem(ViewGroup container, int position) {
     DataFragment fragment = (DataFragment) super.instantiateItem(container, position);
     fragments[position] = fragment;
     return fragment;
 }

这篇关于FragmentPagerAdapter - 如何处理取向的变迁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆