我有一个带有 RecyclerView
的 Fragment
。我的 fragment 调用 AsyncTask
,请求完成后,任务返回到我的 fragment ,该 fragment 实现了 processFinish
方法。在我的 processFinish
中,我引用了一个全局 RV 对象并尝试更新其内容
@Override
public void processFinish(String output, String id) {
switch (id){
case "exchange": {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new
InputStreamReader( new ByteArrayInputStream(output.getBytes()) ));
Type type = new TypeToken<ExchangeResponse>(){}.getType();
ExchangeResponse data = gson.fromJson(reader, type);
homeRV.refreshDrawableState();
// This add doesn't work...
((DisplayableAdapter)homeRV.getAdapter()).addItem(new ExchangeDisplayable(data));
}
}
}
这是我的 addItem
方法。
public void addItem(Displayable d){
this.results.add(d);
this.notifyItemInserted(results.size() - 1);
this.notifyDataSetChanged();
}
如果我从 onViewCreated
更新适配器,它会很好地工作。但不是来自 processFinish
。我在添加项目后立即停止了调试器,并且似乎引用没有丢失(就像其他发布了类似问题的人一样)。我的数据集的大小发生了变化,但视觉上没有任何反应。
编辑 - 我添加了定义 homeRV
的 onViewCreated
和我的 onPostExecute
。
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
homeRV = getView().findViewById(R.id.rv_home);
homeRV.setHasFixedSize(true);
homeRV.addItemDecoration(new DividerItemDecoration(homeRV.getContext(), DividerItemDecoration.VERTICAL));
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getContext());
homeRV.setLayoutManager(layoutManager);
homeRV.setAdapter(new DisplayableAdapter(new ArrayList<Displayable>()));
// This add works...
((DisplayableAdapter)homeRV.getAdapter()).addItem(new HomeDisplayable("Heads up", "this is where Heads Up info will be stored"));
getExchangeRates();
}
在异步任务中:
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
response.processFinish(result, identifier);
}
最佳答案
删除 homeRV.setHasFixedSize(true);
并查看它是否有效。由于这一行,它不会更新 recyclerview 的宽度/高度,因此您看不到新项目。
有关 setHasFixedSize 如何工作的更多信息,请参见 here .
关于java - AsyncTask 之后 RecyclerView 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57347215/