RecyclerView中的筛选功能

huangapple go评论66阅读模式
英文:

Filter in RecyclerView

问题

我有一个已初始化数据的RecyclerView,类似这样:

数据类 ObjectData(
    var name: String,
    var pass: Boolean
) : Serializable

我正在使用 ArrayList 初始化适配器。在我的活动中,我有一个筛选器(全部,已通过,未通过)。当我点击其中一个筛选器时,我希望RecyclerView根据“pass”的值刷新新数据。例如:在“已通过”筛选按钮上,它将仅显示pass为true的 ObjectData。

问题:对此最佳的方法是什么?我可以保留3个列表视图,一个包含所有数据,一个包含已通过的对象,一个包含未通过的对象,并在更改筛选器时使用所需列表更新适配器。但这会导致数据重复。我可以在筛选器上将所有数据复制到新的筛选列表,但这会在每次按钮筛选点击时触发复制,并且用户可能会快速更改筛选器。

你有什么建议。

英文:

I have RecyclerView witch initialized with data like this:

data class ObjectData(
    var name: String,
    var pass: Boolean
) : Serializable

I am Initialing the Adapter with ArrayList<ObjectData>. In my Activity I have filter (All, Passed, No Passed). When I click one of the filters I wish that RecyclerView refresh with new data regarding the "pass" value. Example: On "Passed" filter button it will show only ObjectData with pass=true.

Question: What is the best approach to this? I can hold 3 list views, one with all data, one with passed objects and one with unpassed, and update adapter with the needed list when filter is changed. But this will cause data duplication. I can on filter copy all data to new filtered list, but it will trigger copy on every button filter click, and the user may change filters rapidly.

What can you suggest.

答案1

得分: 1

我只会翻译代码部分,不会回答关于翻译的问题。

我只会翻译代码部分不会回答关于翻译的问题
英文:

I would simply create copies lazily and cache them for example like this:

data class ObjectData(
    var name: String,
    var pass: Boolean
) : Serializable

val allData: List&lt;ObjectData&gt; = emptyList()

val filteredData: Map&lt;Boolean, List&lt;ObjectData&gt;&gt; by lazy {
    allData.groupBy { it.pass }
}

This way you'll create both filtered lists in one go and only when you need them.

Honestly if data set is not big i wouldn't really optimise prematurely unless i see performance is bad. Nowadays Android has much better memory handling.

huangapple
  • 本文由 发表于 2020年8月26日 01:55:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63584578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定