Skip to main content

How to implement filtering in a RecyclerView in Kotlin Android

How to implement filtering in a RecyclerView in Kotlin Android.

Here's a step-by-step tutorial on how to implement filtering in a RecyclerView in Kotlin for Android:

  1. Create a new Android project in Kotlin and add the necessary dependencies to your app's build.gradle file. You will need the RecyclerView library:
implementation 'androidx.recyclerview:recyclerview:1.2.0'
  1. Create a new layout file for the items in your RecyclerView. This layout will represent each item in the list. For example, let's create a layout called "item_layout.xml" with a TextView to display the item's name:
<!-- item_layout.xml -->
<TextView
android:id="@+id/itemNameTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:padding="8dp" />
  1. Create a data class to represent the items in your RecyclerView. This class will hold the necessary data for each item. For example, let's create a data class called "Item" with a single property "name":
data class Item(val name: String)
  1. Create an adapter class for your RecyclerView. This adapter will be responsible for creating the views for each item in the list. It will also handle filtering the data based on user input. Create a new Kotlin class called "ItemAdapter" and implement the following code:
class ItemAdapter(private val items: List<Item>) : RecyclerView.Adapter<ItemAdapter.ItemViewHolder>(), Filterable {

private var filteredItems: List<Item> = items

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return ItemViewHolder(view)
}

override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val item = filteredItems[position]
holder.itemView.itemNameTextView.text = item.name
}

override fun getItemCount(): Int {
return filteredItems.size
}

override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults {
val query = constraint?.toString()?.toLowerCase(Locale.ROOT)
val filteredList = if (query.isNullOrEmpty()) {
items
} else {
items.filter { it.name.toLowerCase(Locale.ROOT).contains(query) }
}
val results = FilterResults()
results.values = filteredList
return results
}

override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
filteredItems = results?.values as? List<Item> ?: emptyList()
notifyDataSetChanged()
}
}
}

class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}
  1. In your activity or fragment, create an instance of the RecyclerView and set up the adapter. Also, create an instance of the search EditText to allow the user to input their filtering criteria. For example, in your MainActivity:
class MainActivity : AppCompatActivity() {

private lateinit var recyclerView: RecyclerView
private lateinit var adapter: ItemAdapter
private lateinit var searchEditText: EditText

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

recyclerView = findViewById(R.id.recyclerView)
searchEditText = findViewById(R.id.searchEditText)

val items = listOf(
Item("Apple"),
Item("Banana"),
Item("Cherry"),
Item("Durian"),
Item("Grape"),
Item("Lemon"),
Item("Orange"),
Item("Pineapple"),
Item("Strawberry"),
Item("Watermelon")
)

adapter = ItemAdapter(items)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)

searchEditText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
adapter.filter.filter(s)
}

override fun afterTextChanged(s: Editable?) {}
})
}
}
  1. Finally, run your app and you should see the RecyclerView with the initial list of items. As you type in the search EditText, the list will automatically filter based on the input.

That's it! You have successfully implemented filtering in a RecyclerView in Kotlin for Android.