之前做项目偶尔会出现这个问题,就是适配器Adapter绑定的数据源改变了,调用notifyDataSetChanged()方法,界面却没反应。然后我发现了问题所在,就是Adapter绑定的数据源的问题。
我以前的错误做法(界面不更新):
下面的栗子是刷新RecyclerView界面,我猜测由于初始化适配器myListAdapter绑定了myListData的内存地址,但更新数据时,myListData的内存地址改变了,所以myListAdapter找不到新的数据了,所以更新界面失败
//1.创建变量myListData
private List<ListItem> myListData;
//2.初始化(以RecyclerView为例)
RecyclerView recyclerView = getActivity().findViewById(R.id.recycler);
GridLayoutManager layoutManager = new GridLayoutManager(this,1);
recyclerView.setLayoutManager(layoutManager);
MyListAdapter myListAdapter = new MyListAdapter(myListData);//绑定myListData内存地址
recyclerView.setAdapter(myListAdapter);
recyclerView.setNestedScrollingEnabled(false);
//3.更新数据-给myListData分配新的内存地址
myListData = new ArrayList<>();
myListItem.add(new ListItem("数据"));
//4.调用notifyDataSetChanged()方法--更新界面失败
myListAdapter.notifyDataSetChanged();
正确做法(界面更新):
//1.先给这个list一个内存地址
private List<ListItem> myListData = new ArrayList<>();
//2.初始化(以RecyclerView为例)
RecyclerView recyclerView = getActivity().findViewById(R.id.recycler);
GridLayoutManager layoutManager = new GridLayoutManager(this,1);
recyclerView.setLayoutManager(layoutManager);
MyListAdapter myListAdapter = new MyListAdapter(myListData);//绑定myListData内存地址
recyclerView.setAdapter(myListAdapter);
recyclerView.setNestedScrollingEnabled(false);
//3.更新数据-内存地址不能改变
myListItem.set(1, new ListItem("data0"));//更改固定位置数据
myListItem.clear();//更改所有数据就先清数据再添加数据
myListItem.add(new ListItem("data"));
//4.最后调用notifyDataSetChanged()方法-更新界面成功
myListAdapter.notifyDataSetChanged();