我的 ListFragment 中有这个很好的方法,我调用它来填写我的其他 fragment 的详细信息:
private void showClientDetails(int pos) {
myCursor.moveToPosition(pos);
int clientId = myCursor.getInt(0);
if(mIsTablet) {
// Set the list item as checked
getListView().setItemChecked(mCurrentSelectedItemIndex, true);
// Get the fragment instance
ClientDetails details = (ClientDetails) getFragmentManager().findFragmentById(R.id.client_details);
// Is the current visible recipe the same as the clicked? If so, there is no need to update
if (details == null || details.getClientIndex() != mCurrentSelectedItemIndex) {
// Make new fragment instance to show the recipe
details = ClientDetails.newInstance(mCurrentSelectedItemIndex, clientId, mIsTablet);
// Replace the old fragment with the new one
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.client_details, details);
// Use a fade animation. This makes it clear that this is not a new "layer"
// above the current, but a replacement
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
}
当用户点击 ListFragment View 中的客户端时调用:
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
mCurrentSelectedItemIndex = position;
showClientDetails(position);
}
这很好用,但是另一个 FragmentActivity 可以更改它显示的数据,所以我认为这会起作用:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//update the client list incase a new one is added or the name changes
if(requestCode==1899)
{
myCursor.requery();
theClients.notifyDataSetChanged();
showClientDetails(mCurrentSelectedItemIndex); //now if client was edited update their details in the details fragment
}
}
现在我知道这行了:
if (details == null || details.getClientIndex() != mCurrentSelectedItemIndex) {
防止在我的 onActivityResult 中调用时到达代码块。因此,如果我删除那个 if
语句,那么事情就会变得异常,ft.commit() 会发出嘶嘶声并给我错误:
`07-08 16:53:31.783: ERROR/AndroidRuntime(2048): Caused by: java.lang.IllegalStateException: onSaveInstanceState 后无法执行此操作
所以我想我想做的事情并不像听起来那么干脆,这对我来说毫无意义,因为我可以整天在 onListItemClicked 上这样做,并且该 fragment 不断显示新点击的客户端的详细信息嗯……
我什至在我的 onActivityResult
中尝试过:
//simulate a click event really fast to refresh the client details
showClientDetails(0);
showClientDetails(mCurrentSelectedItemIndex);
那什么都不做,我是在尝试从 onActivityResult 调用一些不是 Ui 线程还是什么的东西?
我的 ListFragment 代码中也有这个
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentListIndex", mCurrentSelectedItemIndex);
}
这就是错误所提示的吗?
最佳答案
另一个 FragmentActivity
的操作正在执行一项任务,该任务需要 Fragment
通过调用 onSaveInstanceState
来保存其状态,以准备正在重建的新实例。例如,当我从一个充满整个屏幕的 fragment 中触发一个 Activity 时,我已经看到了这一点,因为这导致 View 与 fragment 分离,需要保存状态等。
您基本上不能在 onSaveInstanceState
和正在重新创建的 fragment 的新实例之间调用 commit
。参见 commit .
至于解决方案,然后要么重新考虑尝试避免 commit
被调用,要么调用 commitAllowingStateLoss
如果你认为它对 UI 没问题对用户进行意外更改。
关于android - 刷新我的 fragment 没有像我想象的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6628215/