How to retrieve selected item from a Spinner in Kotlin Android
How to retrieve selected item from a Spinner in Kotlin Android.
Here's a step-by-step tutorial on how to retrieve the selected item from a Spinner in Kotlin Android:
Step 1: Create a Spinner in your layout file
- Open your layout file (e.g., activity_main.xml) in the res/layout folder.
- Add a Spinner element to your layout using the XML code below:
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Step 2: Initialize the Spinner in your activity
- Open your activity file (e.g., MainActivity.kt).
- Declare a variable for the Spinner and initialize it in the onCreate method:
val spinner: Spinner = findViewById(R.id.spinner)
Step 3: Create a list of items for the Spinner
- Declare a variable to hold the list of items for the Spinner in your activity:
val items = listOf("Item 1", "Item 2", "Item 3", "Item 4")
Step 4: Create an ArrayAdapter and set it to the Spinner
- Create an ArrayAdapter to populate the items into the Spinner:
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, items)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
Step 5: Retrieve the selected item from the Spinner
- To retrieve the selected item from the Spinner, add an item selection listener to the Spinner:
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
val selectedItem = parent.getItemAtPosition(position).toString()
// Do something with the selected item
}
override fun onNothingSelected(parent: AdapterView<*>) {
// Do nothing
}
}
In the onItemSelected method, the parent parameter represents the Spinner, and you can use the getItemAtPosition(position) method to retrieve the selected item at the given position. You can then convert it to a String using the toString() method.
That's it! You have successfully retrieved the selected item from a Spinner in Kotlin Android. You can now use the selected item for further processing or display it in your application as needed.
Note: Make sure to replace "Item 1", "Item 2", etc., with your actual items in the list.