0

我们有一个通过 HTTP Post 提供 XML 文件的 Web 服务。

我正在下载这个 xml 文件并将其解析为一个对象,以在FragmentPagerAdapter. 我通过 an 获取此 XML 文件AsyncTask,它通过侦听器接口告诉我的片段该过程已完成。

从那里,我使用从 Web 服务返回的数据填充片段内的视图。这一切都很好,直到方向改变。据我了解,ViewPager的适配器应该保留它创建的片段,这很好,并且我想要发生,并且我知道onCreateView仍然调用片段的方法来返回视图。我花了最后一天左右的时间在这里搜索帖子和谷歌文档等,但我找不到让我做我想做的事情的具体方法:保留片段,它已经填充了视图,这样我就可以只需在方向改变时恢复它并避免对 Web 服务的不必要调用。

一些代码片段:

在主要活动中onCreate

mViewPager = (ViewPager) findViewById(R.id.viewpager);
if (mViewPager != null) {
    mViewPager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
}

if (savedInstanceState == null) {
    if (CheckCredentials()) {
        Refresh(0,0);
    } else {
        ShowCredentialsDialog(false);
    }
}

主要活动中的刷新方法...

public void Refresh(Integer month, Integer year) {
    if (mUpdater == null) {
        mUpdater = new UsageUpdater(this);
//        mUpdater.setDataListener(this);
    }

    if (isConnected()) {
        mUpdater.Refresh(month, year);
        usingCache = false;
        mProgress.show();
    } else {
        mUpdater.RefreshFromCache();
        usingCache = true;
    }
}

这是有问题的整个片段,减去一些 UI 填充代码,因为在 textview 等中显示文本设置并不重要......

public class SummaryFragment extends Fragment implements Listeners.GetDataListener {

    private static final String KEY_UPDATER = "usageupdater";
    private UsageUpdater mUpdater;
    private Context ctx;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.ctx = activity;
    }

    private View findViewById(int id) {
        return ((Activity)ctx).findViewById(id);
    }

    public void onGetData() {
        // AsyncTask interface method, will be called from onPostExecute.
        // Populate view from here
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_usagesummary, container, false);
        mUpdater = (UsageUpdater) getArguments().getSerializable(KEY_UPDATER);
        mUpdater.setDataListener(this);
        return view;
    }
}

如果我理解这个“问题”中的任何一个,那就是我正在返回一个空视图,onCreateView但我不知道如何保留片段,返回它的视图预填充了数据并管理从主要活动调用的所有 Web 服务。

如果你不知道,Android 对我来说不是主要语言,这可能看起来一团糟。任何帮助表示赞赏我变得相当沮丧。

4

1 回答 1

0

如果您在重新创建 Activity 时没有使用任何替代资源,您可以尝试通过在 AndroidManifest 中使用 configChange 标志自己处理旋转事件:

<activity
    ...
    android:configChanges="orientation|screenSize"
    ... />

如果您的 Activity 被重新创建,则无法保持相同的预填充视图,因为这会导致 Context 泄漏:

http://www.curious-creature.org/2008/12/18/avoid-memory-leaks-on-android/

于 2013-08-05T02:44:22.730 回答