当用户返回原始 Activity 后调用 onActivityResult()
时,我会更新 RecyclerView
的数据并调用 notifyDataSetChanged()
但是 onBindViewHolder()
没有被调用并且 RecyclerView
没有更新。
如果我运行相同的代码从 onClick()
触发更新 Recylerview,RecyclerView
会 正确更新。只有当 onActivityResult()
调用更新代码时,RecylerView
才不会更新。
我尝试通过使用 runOnUiThread()
方法运行更新方法来更新 RecylerView
,但这并没有解决问题。我还尝试了 RecyclerView.Adapter
的所有相关通知方法(即 notifyDataSetChanged()
等),但我只会引用 notifyDataSetChanged
为简单起见。
这里是问题的基本重现:
//This code is in the Adapter, it removes an item from the arrayList and updates the RecylerView.
protected void refreshData(int position){
arrayListData.remove(position);
notifyDataSetChanged ();
}
//This code is in the ViewHolder. When refreshData() is called via the onClick() here the **RecylerView does successfully update**
@Override
public void onClick(View v) {
if (shouldRefreshData == true) {
refreshData(getAdapterPosition());
} else {
Intent secondActivity = new Intent(context, SecondActivity.class);
((Activity)context).startActivityForResult(secondActivity, Adapter.REQUEST_CODE);
}
}
//I set the result code is in the Second Activity like this
setResult(Adapter.REQUEST_CODE, usefulIntent);
//This code is in the original activity, it successfully runs, and the refreshData() method is called and I can see the data has been removed via log statements in the refreshData() method but the onBindViewHolder() method is never called
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (requestCode == Adapter.REQUEST_CODE) {
....
adapter.refreshData(positionRetrievedFromTheDataIntent);
}
}
由于 refreshData()
方法在通过 onClick()
触发器调用时确实正确更新了 RecyclerView
似乎该方法配置正确。我尝试向 onActivityResult
添加延迟,这将使 RecylervView
有时间在运行 refreshData()
方法之前加载任何数据,但这并没有解决问题。
任何人都可以在我的代码中看到任何问题或告诉我如何解决这个问题吗?
我查看了其他 SO 问题,但找不到适用于此问题的解决方案。
提前致谢
最佳答案
确保您已调用:
finish();
在 setResult
之后:
setResult(Adapter.REQUEST_CODE, usefulIntent);
为了触发onActivityResult
。
另外如果:
notifyDataSetChanged();
不工作考虑重置
setAdapter();
关于java - 从 onActivityResult() 调用时,notifyDataSetChanged() 不适用于我的 RecyclerView.Adapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37909386/