【发布时间】:2016-10-20 22:24:36
【问题描述】:
当用户返回原始活动后调用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 问题,但找不到适用于该问题的解决方案。
提前致谢
【问题讨论】:
-
我运行了一个简单的测试,它只是工作,尝试调试你的
onActivityResult代码 -
感谢您的回复。我将查看我的 onActivityResult() 设置
-
从 Log 语句中可以看到 onActivityResult() 是使用预期的 requestCode 调用的,而 refreshData() 是由 onActivityResult() 触发的,我可以看到数据从 arrayList 中删除,但是在调用 notifyDataSetChanged() 后不会调用 onBindViewHolder
标签: java android android-recyclerview onactivityresult notifydatasetchanged