使用装载机:
创建 AsyncLoader 的子类并在 Fragment 的 onActivityCreated 实现中启动/初始化这些加载器:
public abstract class MyLoader extends AsyncTaskLoader<String> {
public MyLoader(Context context) {
super(context);
}
private String result;
protected String error;
@Override
public final String loadInBackground() {
try {
error = null;
// Load your data from the server using HTTP and store result as string in 'result'.
...
result = ...
...
return result;
}
catch (Exception e) {
Logger.e("ResourceLoader", "Loading resource failed.", e);
error = e.getMessage();
}
return null;
}
@Override
protected void onStartLoading() {
if (!TextUtils.isEmpty(error)) {
deliverResult(result);
}
if (takeContentChanged()) {
forceLoad();
}
}
@Override
public void deliverResult(String data) {
if (isReset()) {
return;
}
result = data;
if (isStarted()) {
try {
super.deliverResult(data);
}
catch(Exception e) {
Log.e("ResourceLoader", "Caught exception while delivering result.", e);
}
}
}
public String getError() {
return error;
}
}
在你的片段中,你可以初始化这个加载器:
public class Fragment1 extends Fragment implements LoaderCallbacks<String> {
....
....
String message;
TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
....
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = ....
...
textView = (TextView)view.findViewById(R.id.....);
textView.setMessage(message); // in case this Fragment1 survived an orientation change.
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(0, getArguments(), this); // Start loading data after activity has been created.
}
@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
return new MyLoader(getActivity()); // Load data using MyLoader
}
@Override
public void onLoadFinished(Loader<String> loader, String result) {
// Here you have the result in 'result'.
message = result;
if (textView != null) {
// Update UI according to result.
textView.setText(message);
....
}
...
}
....
}
在 onLoadFinished 中,您将结果存储在“消息”中。如果一个简单的 String 结果不够用,您可以更改 MyLoader 和 LoaderCallbacks 以返回和处理更复杂的数据结构(例如 List<String>)。