我使用没有任何布局的片段(它在后台下载文件)。我在第一次创建活动时添加它一次,假设它将在屏幕方向后再次附加,但事实并非如此!
创建活动:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(new FragmentDownloadApp(), FragmentDownloadApp.TAG)
.commit();
} else {
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
片段 onActivityCreated:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// this is really important in order to save the state across screen
// configuration changes for example
setRetainInstance(true);
// ---- magic lines starting here -----
// call this to re-connect with an existing
// loader (after screen configuration changes for e.g!)
LoaderManager lm = getLoaderManager();
if (lm.getLoader(LOADER_DOWNLOAD_APP) != null) {
lm.initLoader(LOADER_DOWNLOAD_APP, null, mDownLoader);
}
// ----- end magic lines -----
}
和错误:
public void onPositiveClick() {
FragmentDownloadApp fragment = (FragmentDownloadApp) getSupportFragmentManager()
.findFragmentByTag(FragmentDownloadApp.TAG);
fragment.startDownload(mAppToDownload);
}
这里出现 NullPointerException!