2

Fragment我想避免在轮换期间加载耗时的数据。

public class WatchlistFragment extends SherlockListFragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (savedInstanceState == null) {
            data = getTimeConsumingData();          
        } else {
            Log.i(TAG, "savedInstanceState is not null!");
            // Avoid performing time consuming data operation during rotation changes.
            // But I never have chance to reach here !?!?
            data = savedInstanceState.getStringArray("data");
        }
        setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, data));
    }

    public String[] getTimeConsumingData() {
        Log.i(TAG, "WatchlistFragment getTimeConsumingData");
        return new String[] { "A", "B", "C"};
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.i(TAG, "WatchlistFragment onSaveInstanceState");
        super.onSaveInstanceState(outState);
        outState.putStringArray("data", data);
    }

    private String[] data = null;
    private static final String TAG = WatchlistFragment.class.getSimpleName();
}

奇怪的是,即使我执行了几次旋转,savedInstanceStateinonActivityCreated也始终为空。

注意,我不喜欢使用setRetainInstance(true)所描述的Android Fragments Retaining Data作者正在使用onSaveInstanceState. 只是我不确定为什么我的不起作用。

4

3 回答 3

1

另一种方法是使用新的、超级聪明的 Loader 模式,它很容易实现并让系统为您处理所有这些:

http://developer.android.com/guide/components/loaders.html

于 2013-02-25T11:09:49.370 回答
0

只需setRetainInstance(true)在您的片段中使用并检查savedInstanceState==null并且不要覆盖onSaveInstanceState

更新

 private ArrayAdapter<String> adapter = null;
 public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setReatainInstance(true);
    if(adapter==null){
        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,getTimeConsumingData());
    }
    setListAdapter(adapter);
}
于 2013-02-25T10:56:27.183 回答
0

如果您正在使用加载器,请在加载数据后使用 loadermanager.destory(loader_id)。它不会再次加载以进行配置更改。

于 2013-02-25T12:43:14.190 回答