【问题标题】:RecyclerView item style applying to all items after filterRecyclerView 项目样式应用于过滤后的所有项目
【发布时间】:2016-05-28 02:04:34
【问题描述】:

RecyclerView 有点问题。

关于 OnBindViewHolderAdapter 方法我正在做一个测试,以定义 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

}

【问题讨论】:

  • 我认为您的问题出在这行代码中 .. holder.layout.setBackgroundResource(R.drawable.recycler_view_selector_colored_item);因为它将颜色设置为整个布局(无论布局是什么)
  • 这个layout 是一个RelativeLayout,其中包含该项目的TextViews。不过我现在就去研究一下,谢谢你的回答。
  • 不,没有用...

标签: android arraylist filter android-recyclerview searchview


【解决方案1】:

我认为你需要在这里添加一个 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] 移除背景

希望这会有所帮助...

【讨论】:

  • 谢谢,它工作得很好。我想也许我可以在不必重新定义布局的情况下做到这一点,但这种方式效果很好。
  • @MidasLefko 看起来不错,但令我惊讶的是,几乎所有关于 RecyclerViews 的文章都将重点放在创建列表上,但没有一个是保存列表。创建一个制作精美/有价值的列表(比如我想下载的一大串歌曲)然后如果我通过单按后退按钮离开列表,那么该列表就会被彻底销毁。为什么不保存状态代码是创建每个 RecyclerView 列表的要求,就像其他要求一样:适配器、布局管理器、onCreateViewHolder、onBindViewHolder 和 getItemCount?想法?
猜你喜欢
  • 2019-06-07
  • 2020-11-02
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多