我在使用 RecyclerView
时遇到了一点问题。
在 Adapter
的方法 OnBindViewHolder
上,我正在做一个测试,定义 RecyclerView
的项目是否应该使用自定义背景颜色。
到目前为止一切正常,问题是,在使用带有 SearchView
的过滤器后,如果我使用自定义背景色过滤一个结果,在清理过滤器/折叠 SearchView
,所有其他项目都获得相同的背景颜色。
这是我的适配器的一些代码:
@Override
public void onBindViewHolder (MyAdapter.VieHolder holder, int position){
holder.textViewName.setText(myVisibleList.get(position).getName());
// myVisibleList is the list that is show in the recyclerView
// If true, is birthday, then change the item background color
if(myVisibleList.get(position).isBirthDay){
holder.layout.setBackgroundResource(R.drawable.recycler_view_selector_colored_item);
}
}
@Override
public Filter getFilter(){return null;}
public void setFilter(String query){
myVisibleList = new ArrayList<>();
// Contact is the object show in the recyclerView / allContacts is the list if all the contacts
for (Contact c : allContacts){
if(c.getName().contains(query)){
myVisibleList.add(c);
}
}
notifyDataSetChanged();
}
// Method to clear the filter / Called when the searchView is closed
public void clearFilter(){
myVisibleList = new ArrayList<>();
myVisibleList.addAll(allContacts);
notifyDataSetChanged
}
最佳答案
我认为您需要在此处添加一个 else 子句:
if (myVisibleList.get(position).isBirthDay){
holder.layout.setBackgroundResource(R.drawable.recycler_view_selector_colored_item);
} else {
holder.layout.setBackgroundResource(R.drawable.my_default_recycler_view_color_item);
// or holder.layout.setBackgroundResource(0);
}
参见 docs上面写着
0 [is] to remove the background
希望这有助于...
关于android - RecyclerView 项目样式应用于过滤后的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35438562/