您应该执行异步任务来加载列表。在替换当前片段之前,只需取消异步任务。如果任务未取消,请确保签入 onPostExecute。
在这里,您可以找到将数据异步加载到回收器视图的示例:http: //javatechig.com/android/android-recyclerview-example。看看 AsyncHttpTask。您可以看到在 doInBackground 上获取和解析数据,并显示在 onPostExecute 中。您还需要在代码中添加以下内容:将 onPostExecute 中的所有内容包含在
if (!isCancelled()) {
/* your code here for setting list adapter */
}
分离时覆盖:
@Override
public void onDetach() {
super.onDetach();
// don't update the UI if user go from this fragment
if (displayResultsAsyncTask != null && !displayResultsAsyncTask.isCancelled())
displayResultsAsyncTask.cancel(true);
}
所以你的代码应该是这样的:
public class YourFragment extends Fragment {
// declare an async task in your fragment
private AsyncTask displayResultsAsyncTask = null;
/* other data here */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* your code for onCreate */
GetAndDisplayResults(); // call display results
}
public void GetAndDisplayResults() {
displayResultsAsyncTask = new AsyncTask<String, Void, Integer>() {
@Override
protected Integer doInBackground(String... params) {
Integer result = 0;
// get and parse data, also set result
return result;
}
@Override
protected void onPostExecute(Integer result) {
if (!isCancelled()) {
// if task wasn't stopped
if (result == 1)
SetYourList(); // set your list adapter based on results returned from doInBackground
}
}
}.execute();
}
@Override
public void onDetach() {
super.onDetach();
// don't update the UI if user go from this fragment
if (displayResultsAsyncTask != null && !displayResultsAsyncTask.isCancelled())
displayResultsAsyncTask.cancel(true);
}
}
用于保存数据的列表可以全局声明并从 doInBackground 和 onPostExecute 访问,也可以作为参数传递给 onPostExecute。