我在我的ListFragment中有一个很好的方法,我调用它来填写另一个片段的详细信息:
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视图中单击客户机时调用它:
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
mCurrentSelectedItemIndex = position;
showClientDetails(position);
}
这样做很好,但是另一个碎片活动可以更改显示的数据,所以我认为这样做可以:
@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) {
防止在My OnActivityResult中调用代码块时访问该代码块。因此,如果我删除了
if
语句,那么事情就会变得异常,ft.commit()会发出嘶嘶声,并给出错误:` 07-08 16:53:31.783:错误/AndroidRuntime(2048):原因:java.lang.IllegalStateException:在OnSaveInstanceState之后无法执行此操作
所以我想我要做的并不像听起来那么简单,这对我来说毫无意义,因为我可以一整天只点击一个列表项,而这个片段总是很好地显示新点击客户端的细节……
我甚至在我的
onActivityResult
里试过这个://simulate a click event really fast to refresh the client details
showClientDetails(0);
showClientDetails(mCurrentSelectedItemIndex);
这没什么用,是我试图从onactivityresult调用不是ui线程的东西还是什么?
我在列表片段的代码中也有这个
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentListIndex", mCurrentSelectedItemIndex);
}
这就是我们抱怨的错误吗?
最佳答案
另一个FragmentActivity
的操作是执行一个任务,该任务要求Fragment
通过调用onSaveInstanceState
来保存其状态,以准备重建新实例。例如,当我从一个填充了整个屏幕的片段中触发一个活动时,我看到了这一点,因为这导致视图与片段分离,状态需要保存等等。
您基本上不能在commit
和要重新创建的片段的新实例之间调用onSaveInstanceState
。参见commit。
至于解决方案,那么要么重新考虑尝试避免在调用commit
时调用它,或者如果您认为用户的ui可以意外更改,则调用commitAllowingStateLoss
。
关于android - 刷新 fragment 无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6628215/