Skip to main content

How to set a default selected item in a Spinner in Kotlin Android

How to set a default selected item in a Spinner in Kotlin Android.

Here is a detailed step-by-step tutorial on how to set a default selected item in a Spinner in Kotlin Android.

Step 1: Create a new Android project

First, open Android Studio and create a new Android project with an empty activity.

Step 2: Add a Spinner to your layout file

Open the layout file (activity_main.xml) and add a Spinner element. For example, you can add the following code inside the LinearLayout element:

<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/planets_array"
/>

In this example, we set the Spinner's id to "spinner" and use the "entries" attribute to populate it with an array of planet names (which we will define later).

Step 3: Define an array of items

Open the strings.xml file (located in the res/values folder) and add an array resource containing the items you want to display in the Spinner. For example, you can add the following code:

<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>

Step 4: Initialize the Spinner in your activity

Open the MainActivity.kt file and add the following code inside the onCreate() method:

val spinner = findViewById<Spinner>(R.id.spinner)
spinner.setSelection(2) // set the default selected item index

In this example, we first retrieve the Spinner view using its id. Then, we use the setSelection() method to set the default selected item index to 2 (which corresponds to "Earth" in the array).

Step 5: Handle item selection events (optional)

If you want to perform some actions when the user selects an item from the Spinner, you can add an OnItemSelectedListener. Here's an example of how to do it:

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 something when nothing is selected
}
}

In this example, we set an anonymous object as the OnItemSelectedListener and override the onItemSelected() and onNothingSelected() methods. Inside the onItemSelected() method, we retrieve the selected item using getItemAtPosition() and perform the desired actions.

Step 6: Run the app

Finally, run the app on an emulator or a physical device. You should see the Spinner with the default selected item already set to "Earth" (or the item at the selected index).

That's it! You have successfully set a default selected item in a Spinner in Kotlin Android.