Filterable

2021. 11. 4. 13:37Android

반응형
class SearchListAdapter(
    private val context: Context,
    private val callback: (String) -> Unit
) : RecyclerView.Adapter<SearchListAdapter.ViewHolder>(), Filterable {
    private var itemList: MutableList<SearchResultItem> = arrayListOf()
    private var itemFilteringList: MutableList<SearchResultItem> = arrayListOf()
    private var itemFilterResultList: MutableList<SearchResultItem> = arrayListOf()
    
    
        override fun getFilter(): Filter {
        return object : Filter() {
            override fun performFiltering(constraint: CharSequence?): FilterResults {
                val filterResults = FilterResults()
                val words = constraint.toString()
                if (words.isNotEmpty()) {
                    if (itemFilteringList.size > 0) {
                        itemFilteringList.clear()
                    }
                    itemList.forEach {
                        if (it.contents.indexOf(words) > 0) {
                            itemFilteringList.add(it)
                        }
                    }
                    filterResults.values = itemFilteringList
                } else {
                    filterResults.values = itemList
                }
                return filterResults
            }

            override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
                results?.let {
                    itemFilterResultList = (it.values as MutableList<SearchResultItem>)
                    notifyDataSetChanged()
                }
            }
        }
    }
    
        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val layoutSearchResult: RelativeLayout = view.findViewById(R.id.layout_search_result)
        val resultContents: TextView = view.findViewById(R.id.result_contents)
        fun bind(view: View, text: String) {
            view.setOnClickListener {
                callback(text)
            }
        }
    }
    
    
    
    }

 

https://smartstore.naver.com/byrollin?

 

바이롤린 : 네이버쇼핑 스마트스토어

내 삶이 즐거워지는 순간, 바이롤린과 함께 ♡

smartstore.naver.com

 

반응형