我有一个活动,显示进度条片段,加载数据,然后在隐藏进度条片段后将其显示在新片段中。
我遇到了臭名昭着的onPostExecute()/配置更改问题,在阅读了大量关于可能解决方案的帖子之后,我发现它们中没有处理onPostExecute()中的切换片段 - 这也可能有潜在危险,因为它可能会抛出尝试在活动保存状态后提交片段事务时出现IllegalStateException。
这是相关代码:
public class MyActivity extends FragmentActivity implements {
class LoadListTask extends AsyncTask<Void, Void, MyListItem> {
@Override
protected void onPreExecute() {
showProgressBar();
}
@Override
protected Response doInBackground(Void... params) {
//
// ... web call
//
return new List<MyListItem>;
}
protected void onPostExecute(List<MyListItem> result) {
if (result != null) {
hideProgressBar();
showList(result);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
new LoadListTask().execute(session);
}
public void showProgressBar() {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.placeholder,
mProgressBarFragment).commit();
fragmentManager.executePendingTransactions();
}
private void hideProgressBar() {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.remove(mProgressBarFragment)
.commit();
fragmentManager.executePendingTransactions();
}
private void showList(List<ListItem> list) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
Fragment frg = FacebookFriendPickerFragment
.newInstance(friendsArrObj);
fragmentTransaction.replace(R.id.friendPickerPlaceholder, frg)
.commit();
fragmentManager.executePendingTransactions();
}
}
我开始认为拥有一个只显示进度的片段使事情变得复杂,但我确实想要坚持片段 - 所以有没有办法“同步”片段事务,所以它会在合理的情况下发生活动生命周期的阶段,并避免AsyncTask / config-change问题?
答案 0 :(得分:1)
您需要将此代码放入您的片段:
// Retain this fragment across configuration changes.
setRetainInstance(true);
有关使用本教程中可以阅读的片段处理配置更改的更多信息:
http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
希望,我帮助你。