FragmentPagerAdapter - 如何处理方向变化? [英] FragmentPagerAdapter - How to handle Orientation Changes?

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

问题描述

我使用了一个 FragmentPagerAdapter,其中包含多个需要通知 database 更改的 Fragment.我通过迭代实现回调接口的片段并调用 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() 即使在方向更改后也会调用该方法并将 Object 转换为 Fragment 并将其保存在您的数组中.

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天全站免登陆