How to filter items in a Spinner based on user input in Kotlin Android
How to filter items in a Spinner based on user input in Kotlin Android.
Here's a step-by-step tutorial on how to filter items in a Spinner based on user input in Kotlin for Android.
Create a new Android project in Android Studio and open the activity_main.xml file.
Add a Spinner view to the layout by adding the following code inside the
<LinearLayout>tag:
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
- Open the MainActivity.kt file and declare a variable to hold the Spinner view:
private lateinit var spinner: Spinner
- Inside the
onCreatemethod, initialize the Spinner view using its ID from the layout:
spinner = findViewById(R.id.spinner)
- Create a list of items that will be displayed in the Spinner. For this tutorial, let's use a list of fruits:
val fruits = listOf("Apple", "Banana", "Cherry", "Grapes", "Orange", "Strawberry")
- Create an ArrayAdapter to populate the Spinner with the list of fruits. Add the following code below the list of fruits:
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, fruits)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
- Implement a TextWatcher to filter the items in the Spinner based on user input. Add the following code below the ArrayAdapter initialization:
val filterTextWatcher = 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?) {}
}
spinner.addTextChangedListener(filterTextWatcher)
Build and run the app on an emulator or device. You should see the Spinner with the list of fruits displayed.
Test the filtering functionality by typing in the Spinner. As you type, the Spinner should filter its items based on the entered text.
Congratulations! You have successfully implemented filtering of items in a Spinner based on user input in Kotlin for Android.