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();
}
奇怪的是,即使我执行了几次旋转,savedInstanceState
inonActivityCreated
也始终为空。
注意,我不喜欢使用setRetainInstance(true)
所描述的Android Fragments Retaining Data作者正在使用onSaveInstanceState
. 只是我不确定为什么我的不起作用。