以前,我有一个Fragment
,它根据耗时的获取数据更新其 UI。
public class HomeMenuFragment extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Infos arg1 = performTimeConsumingDataStructureLoading();
// Add in various UI views in v, according to information in loaded
// data structure.
View v = inflater.inflate(R.layout.home_menu, container, false);
// ...
// Adding several LinearLayout and TextView into v, based on
// information from loaded data structure (arg1)
// ...
return v;
}
....
}
这真的不是一个好的设计。有时,performTimeConsumingDataStructureLoading
可能需要超过 5 秒,我会得到 ANR(应用程序无响应)
通过参考http://developer.android.com/reference/android/content/AsyncTaskLoader.html,我最终得到了更好的解决方案。我遇到的例子是,它通过ArrayAdapter
.
public class HomeMenuFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<HomeMenuFragment.Infos> {
@Override
public void onLoadFinished(Loader<Infos> arg0, Infos arg1) {
LayoutInflater inflater = this.getLayoutInflater(null);
ViewGroup container = (ViewGroup)this.getView().getParent();
// Remove previous old views, as onLoadFinished might be triggered
// by onContentChanged too.
container.removeAllViews();
View v = inflater.inflate(R.layout.home_menu, container, false);
// ...
// Adding several LinearLayout and TextView into v, based on
// information from loaded data structure (arg1)
// ...
container.addView(v);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
....
}
我没有,ArrayAdapter
因为我没有使用ListFragment
. 我想要做的是将几个TextView
加到几个LinearLayout
中。然后,我将添加LinearLayout
到Fragment
's 容器中。
但是,以下代码给了我空指针异常。
ViewGroup container = (ViewGroup)this.getView().getParent();
我知道在onLoadFinished
from之后动态更新 Fragment UI 的正确方法是什么AsyncTaskLoader
?