How you can create a dynamic spinner in Kotlin Android | Custom spinner in Android

How you can create a dynamic spinner in Kotlin | Custom spinner in Android

  1. In your layout XML file, add a Spinner element to the layout.
<Spinner android:id="@+id/spinner" android:layout_width="match_parent" android:layout_height="wrap_content" />
  1. In your activity or fragment, find the Spinner element by its ID.
val spinner = findViewById<Spinner>(R.id.spinner)
  1. Create a list of items to display in the spinner.
val items = listOf("Item 1", "Item 2", "Item 3")
  1. Create an ArrayAdapter for the spinner, and set the adapter to 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
    1. (Optional) Set a listener for when an item is selected in the spinner.
    spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { // Do something with the selected item } override fun onNothingSelected(parent: AdapterView<*>)
    }}

    Note that this is a basic example, and you may want to customize the layout of the spinner items and handle the selected item in a more complex way.

    Previous Post Next Post