Android:正确处理ViewPager和数据密集型片段的方法?

时间:2013-12-13 16:38:11

标签: android caching android-fragments android-viewpager fragmentpageradapter

我正试着用ViewPager正确使用片段。我目前有5个片段(有一个主要活动),每个片段从Web服务中提取一些数据并将其显示给用户。用户可以在视图之间滑动以查看不同的信息。我遇到的问题是,一旦用户滑动两页然后返回到片段,片段就会被破坏并重新创建,从而导致在不需要时多次调用Web服务。配置更改还会强制重新创建片段(从而调用Web服务)。我目前正在重新创建片段的新实例。什么是缓存数据的最佳方法?或者我是以错误的方式使用FragmentPagerAdapter?我附上了一些相关的代码。

 @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                WebFragmentOne a = WebFragmentOne.newInstance();
                return a;

            case 1:
                WebFragmentTwo b = WebFragmentTwo.newInstance();
                return b;

            case 2:
                WebFragmentThree c = WebFragmentThree.newInstance();
                return c;

            case 3:
                WebFragmentFour d = WebFragmentFour.newInstance();
                return d;

            case 4:
                WebFragmentFive f = WebFragmentFive.newInstance();
                return f;
        }
        return null;
    }

每个片段中的newInstance()方法。

public static final WebFragment newInstance()
{
    WebFragment f = new WebFragment();
    return f;
}

1 个答案:

答案 0 :(得分:1)

将要保留的数据保留在片段中的私有字段中。

在OnCreate调用setRetainInstance(true)中停止Android销毁你的片段。

现在,如果已有数据,您可以检查片段何时开始。如果不这样做,则可以从Web服务中检索它。如果您这样做,则跳过检索并直接跳转到您的视图设置。