我有一个显示进度条片段的活动,加载数据,然后在隐藏进度条片段后将其显示在新片段中。
我遇到了臭名昭著的 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 问题?