How to Use Spinner and add Drop Down List Items in Android Studio?

In Android, Spinner is used to select one value from a Spinner using a drop down list.

Android spinner is associated with AdapterView. So we need to set the adapter class with the Spinner.

MainActivity.java

package com.example.spinner;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
Spinner spinner;
TextView textView,textView1;
String str[]={"PHP","JAVA","ANDROID","JAVA SCRIPT","JQUERY"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner=findViewById(R.id.spinner);
textView=findViewById(R.id.textview);
textView1=findViewById(R.id.textview1);
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_dropdown_item_1line,str);
spinner.setAdapter(arrayAdapter);
}
}
 

XML Design

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"

android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.549"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.36">

<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="50dp"
android:text="Spinner"
android:textColor="#F10909"
android:textSize="23dp"
android:textStyle="bold" />

<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="60dp"
android:textSize="15dp"
android:textColor="#110000"
android:text="Courses :" />

<Spinner
android:id="@+id/spinner"
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_margin="10dp"
android:textColor="#FBFBFB" />
</LinearLayout>


</androidx.constraintlayout.widget.ConstraintLayout>

Code Result

Amandeep kaur: Amandeep Kaur is passionate about programming and is working on Android development from her school days. She has worked on many open source projects and now part of Hoodu Digital solutions as a Android developer.