Spinner - Android Studio - Compose

How to use the Spinner in Android Studio with Compose

In this tutorial, you’ll learn how to use a Spinner in Android Studio using Jetpack Compose. A Spinner in Android works like a drop-down menu that displays a list of values, allowing the user to select one option at a time.

The Android Spinner is part of the AdapterView family, which means it requires an Adapter to bind data to the UI. In this example, we’ll use an adapter to populate the Spinner with items and handle user selection events.

Code:

MainActivity.kt

package com.technifysoft.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.technifysoft.myapplication.ui.theme.MyApplicationTheme

class MainActivityCompose : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            SpinnerUI()
        }
    }

    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun SpinnerUI() {
        // 1. Data Source
        val options = listOf("Canada", "Pakistan", "Turkey", "US")

        // 2. State Management (Replaces member variables)
        // 'expanded' tracks if the dropdown is open
        var expanded by remember { mutableStateOf(false) }
        // 'selectedOption' tracks the current selection
        var selectedOption by remember { mutableStateOf(options[0]) }

        // 3. Layout Container (Replaces LinearLayout)
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(10.dp), // Padding from XML
            horizontalAlignment = Alignment.CenterHorizontally // Centers items horizontally
        ) {

            // --- Title TextView ---
            Text(
                text = "Spinner",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(vertical = 40.dp)
            )

            // --- Spinner Replacement (ExposedDropdownMenuBox) ---
            ExposedDropdownMenuBox(
                expanded = expanded,
                onExpandedChange = { expanded = !expanded },
                modifier = Modifier.fillMaxWidth()
            ) {
                // The text field showing the current selection
                OutlinedTextField(
                    value = selectedOption,
                    onValueChange = {}, // Read-only
                    readOnly = true,
                    trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
                    colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors(),
                    modifier = Modifier
                        .menuAnchor() // REQUIRED: links menu to this text field
                        .fillMaxWidth()
                )

                // The list of items
                ExposedDropdownMenu(
                    expanded = expanded,
                    onDismissRequest = { expanded = false }
                ) {
                    options.forEach { option ->
                        DropdownMenuItem(
                            text = { Text(text = option) },
                            onClick = {
                                selectedOption = option // Update state
                                expanded = false // Close menu
                            },
                            contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding
                        )
                    }
                }
            }

            // --- Output TextView ---
            Spacer(modifier = Modifier.height(20.dp)) // Adds a bit of space

            Text(
                text = "$selectedOption is selected...",
                fontSize = 30.sp,
                color = Color.Black
            )
        }
    }

    /**
     * GreetingPreview is a composable function for previewing the MainUI in Android Studio.
     * It is annotated with @Preview to enable live preview.
     *
     */
    @Preview(showBackground = true)
    @Composable
    private fun GreetingPreview() {
        MyApplicationTheme {
            SpinnerUI()
        }
    }

}

Screenshots:



Comments

Popular posts from this blog

Picture In Picture - Android Studio - Kotlin

Manage External Storage Permission - Android Studio - Kotlin

SeekBar with Customization | Android Studio | Java