Last active
June 20, 2020 11:51
-
-
Save R00We/731a2a5d76bcb2a92adcd6da60e0cd12 to your computer and use it in GitHub Desktop.
ListAdapter by RecyclerView with implementation Filterable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class FilterableListAdapter<Item>( | |
callback: DiffUtil.ItemCallback<Item> | |
): ListAdapter<Item, RecyclerView.ViewHolder>(callback), Filterable { | |
protected val rawItems = mutableListOf<Item>() | |
protected var itemsNotFound: Boolean = false | |
override fun getFilter(): Filter { | |
return object: Filter(){ | |
override fun performFiltering(constraint: CharSequence): FilterResults { | |
val filerResults = FilterResults() | |
val items = if (constraint.isEmpty()) { | |
rawItems | |
} else { | |
rawItems.filter { | |
isFilter(it, constraint) | |
} | |
} | |
filerResults.values = items | |
filerResults.count = items.size | |
return filerResults | |
} | |
override fun publishResults(constraint: CharSequence, results: FilterResults) { | |
itemsNotFound = results.count == 0 | |
publishResult(results.values as List<Item>) | |
} | |
} | |
} | |
private fun publishResult(items: List<Item>){ | |
super.submitList(items) | |
} | |
private fun fillRawItems(list: List<Item>?){ | |
rawItems.clear() | |
list?.let { | |
rawItems.addAll(list) | |
} | |
} | |
override fun submitList(list: List<Item>?) { | |
fillRawItems(list) | |
super.submitList(list) | |
} | |
override fun submitList(list: MutableList<Item>?, commitCallback: Runnable?) { | |
fillRawItems(list) | |
super.submitList(list, commitCallback) | |
} | |
abstract fun isFilter(item: Item, constraint: CharSequence): Boolean | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment