Android Spinner is used to display the multiple options in which the user can select only one item. In other words Spinner is like as drop-down menu.
1. activity_main.xml
<?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">
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:gravity="left"
android:layout_toRightOf="@+id/spinnertxt"
>
</Spinner>
<TextView
android:id="@+id/spinnertxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:layout_marginLeft="20dp"
android:textColor="#000"
android:layout_marginTop="25dp"
/>
</RelativeLayout>
2. MainActivity.java
package com.example.spinner;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Spinner spinner;
List<String> list;
ArrayAdapter<String> SpinnerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner)findViewById(R.id.spinner);
list = new ArrayList<String>();
list.add("Select your Favorite Color");
list.add("Blue");
list.add("White");
list.add("Red");
list.add("Green");
list.add("Black");
list.add("Yellow");
list.add("Pink");
list.add("Orange");
SpinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list){
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
((TextView)v).setTextColor(getResources().getColor(R.color.colorPrimary));
return v;
}
@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View v = super.getDropDownView(position, convertView, parent);
v.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
return v;
}
};
SpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(SpinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String state = adapterView.getItemAtPosition(i).toString();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}