Create a simple example of using a Spinnerin Android. In this example, we'll create an Android app with a Spinner, and the user can set the select data using the Spinner. We'll also display a toast message with the selected Spinner.
There Are Some Common Attributes for Spinner:
id | This ID serves as the control's unique identity. |
layout_width | match_parent -> Text area contains fullscreen wrap_content-> Text area contains only text size |
layout_width | match_parent -> Text area contains fullscreen wrap_content-> Text area contains only text size |
Step 1:
File open res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Spinner
android:id="@+id/spinner"
android:layout_width="200dp"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
Step 2:
File open com.microappvalley.newtestproject/MainActivity.kt file −
package com.microappvalley.newtestproject
import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Spinner
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var spinner: Spinner
var spinnerArray= arrayOf("Java","Kotlin","JetPack","Flutter")
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
spinner= findViewById(R.id.spinner)
val adapter=ArrayAdapter(this,android.R.layout.simple_expandable_list_item_1,spinnerArray)
spinner.adapter=adapter
}
}
Open Device Manager, run the emulator, and then run the application. Next, check the working output and check the output you declared in your code.