[英]RecyclerView not updating after AsyncTask
我有一个带有RecyclerView
的Fragment
。 我的片段调用AsyncTask
,请求完成后,任务返回到我的片段, processFinish
片段实现了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
。 添加项目后,我立即停止了调试器,似乎参考没有丢失(就像其他发布了类似问题的人一样)。 我的数据集的大小已更改,但在视觉上什么也没有发生。
编辑 -我添加了在其中定义onViewCreated
homeRV
和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();
}
在AsyncTask中:
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
response.processFinish(result, identifier);
}
删除homeRV.setHasFixedSize(true);
看看是否可行。 由于此行,它不会更新recyclerview的宽度/高度,因此您看不到新项目。
有关setHasFixedSize如何工作的更多信息,请参见此处 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.