在http://developer.android.com/guide/components/loaders.html上的 Loaders的Android文档中,它说加载器的一个属性是:
在配置更改后重新创建时,它们会自动重新连接到最后一个加载器的光标.因此,他们不需要重新查询他们的数据.
以下代码似乎没有镜像该行为,创建一个新的Loader完成查询ContentResolver,然后我旋转屏幕并重新创建Loader!
public class ReportFragment extends Fragment implements LoaderCallbacks<Cursor> {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLoaderManager().initLoader(1, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_report, container, false);
return v;
}
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
Log.d("TEST", "Creating loader");
return new CursorLoader(getActivity(), ResourcesContract.Reports.CONTENT_URI, null, null, null, null);
}
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
Log.d("TEST", "Load finished");
}
public void onLoaderReset(Loader<Cursor> arg0) {
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的logcat的输出:
08-17 16:49:54.474: D/TEST(1833): Creating loader
08-17 16:49:55.074: D/TEST(1833): Load finished
*Here I rotate the screen*
08-17 16:50:38.115: D/TEST(1833): Creating loader
08-17 16:50:38.353: D/TEST(1833): Load finished
Run Code Online (Sandbox Code Playgroud)
知道我在这里做错了吗?
编辑:
我应该注意,我正在构建Android Google API的版本8,并使用v4支持库.
第二次编辑:
这很可能是由于支持库中的错误,如果您想了解更多信息,请查看此错误提交:
ain*_*aur -3
onCreate() 在屏幕方向更改期间被调用,因为 Activity 被销毁并重新创建。
除非您要加载大量数据,否则这样做并没有什么坏处,但如果您愿意,可以尝试以下操作(我还没有测试过,但理论上我认为它会起作用)。
在类的顶部全局声明一个静态布尔值。我想你还需要一个静态光标来引用
private static boolean dataDownloaded = false;
private static Cursor oldCursor;
Run Code Online (Sandbox Code Playgroud)
然后在 onLoadFinished 设置 dataDownloaded = true
重写 onSaveInstanceState 以保存布尔值
@Override
protected void onSaveInstanceState(Bundle outSave) {
outSave.putBoolen("datadownloaded", dataDownloaded);
oldCursor = adapter.swapCursor(null);
}
Run Code Online (Sandbox Code Playgroud)
并在 onCreate 添加以下内容
if (savedInstanceState != null) {
this.dataDownloaded = savedInstanceState.getBoolean("datadownloaded", false);
}
Run Code Online (Sandbox Code Playgroud)
调整你的 onCreateLoader
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader;
if (dataDownloaded) {
cursorLoader = new CursorLoader(getActivity(),
null, projection, null, null, null);
cursorLoader.deliverResult(oldCursor);
} else {
CursorLoader cursorLoader = new CursorLoader(getActivity(),
URI_PATH, projection, null, null, null);
}
return cursorLoader;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10130 次 |
| 最近记录: |