How to create a Spinner with RadioButton using Kotlin- Custom Dropdown Menu

Use Kotlin to create a unique dropdown menu. I’ve implemented a custom spinner using RadioButton in Kotlin in this blog post.

The selected item will be displayed in the spinner and a toast message will display in the selection when the user select an item form a dropdown menu.

πŸ“ Project Structure

We will working with this project:

MainActivity.kt – To handle UI Logic
Radio Adapter – a custom adapter for the spinner
spiner_item – layout from dropdown

Step 1 :- Create a Spinner Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dp">

    <RadioButton
        android:id="@+id/radio_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:text="Select Degree"
        android:textSize="15sp"
        android:focusableInTouchMode="false"
        android:clickable="false"/>
</LinearLayout>

Step2: Create A Spinner in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/select_degree"
            android:textSize="20sp" />

        <androidx.appcompat.widget.AppCompatSpinner
            android:id="@+id/spinner_degree"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:textSize="20sp" />

    </LinearLayout>
</LinearLayout>

Step3: Kotlin Code for MainActivity.kt

package com.programmingkeeda.spinnerwithradiobuttonkotlin

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.Spinner
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var spinner: Spinner
    private lateinit var radioAdapter: RadioAdapter

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

        spinner = findViewById(R.id.spinner_degree)

        val degrees = listOf(
            "Select Degree",  // default first item
            "Diploma", "Bachelor of Engineering (BE/B.Tech)",
            "Bachelor of Science (B.Sc)", "Bachelor of Commerce (B.Com)",
            "Bachelor of Arts (BA)", "Bachelor of Business Administration (BBA)",
            "Bachelor of Computer Applications (BCA)", "Master of Business Administration (MBA)",
            "Master of Computer Applications (MCA)", "Master of Science (M.Sc)"
        )

        spinner.post {
            spinner.dropDownVerticalOffset = spinner.height
        }

        radioAdapter = RadioAdapter(this, degrees)
        spinner.adapter = radioAdapter

        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
                radioAdapter.setSelectedPosition(position)
                Toast.makeText(this@MainActivity, "Selected: ${degrees[position]}", Toast.LENGTH_SHORT).show()
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }
    }
}

Step4:- Create A Radio Adapter for Custom Spinner Adapter

package com.programmingkeeda.spinnerwithradiobuttonkotlin

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.RadioButton
import android.widget.TextView

class RadioAdapter(
    private val context: Context,
    private val items: List<String>
) : BaseAdapter() {

    private var selectedItem: Int = 0

    override fun getCount(): Int = items.size

    override fun getItem(position: Int): Any = items[position]

    override fun getItemId(position: Int): Long = position.toLong()

    fun setSelectedPosition(position: Int) {
        selectedItem = position
        notifyDataSetChanged()
    }

    fun getSelectedPosition(): Int = selectedItem

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        // Spinner selected item view
        val textView = TextView(context)
        textView.setPadding(16, 16, 16, 16)
        textView.text = items[position]
        return textView
    }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = LayoutInflater.from(context).inflate(R.layout.spinner_item, parent, false)
        val radioButton = view.findViewById<RadioButton>(R.id.radio_button)
        radioButton.text = items[position]
        radioButton.isChecked = position == selectedItem
        return view
    }
}

When the app runs:

A Drop Down Appears with degree options
Selecting an item form RadioButton showing toast.

Leave a Reply

Your email address will not be published. Required fields are marked *