https://android--code.blogspot.com/2015/08/android-spinner-set-selected-item.html
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#83b3cd"
>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Third Item From Spinner"
/>
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn"
/>
</RelativeLayout>
spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textStyle="italic"
android:fontFamily="sans-serif-medium"
android:background="#fcba14"
/>
MainActivity.java
package com.cfsuman.me.androidcodesnippets;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get reference of widgets from XML layout
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
Button btn = (Button) findViewById(R.id.btn);
// Initializing a String Array
String[] plants = new String[]{
"Laceflower",
"Sugar maple",
"Mountain mahogany",
"Butterfly weed"
};
final List<String> plantsList = new ArrayList<>(Arrays.asList(plants));
// Initializing an ArrayAdapter
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this,R.layout.spinner_item,plantsList);
spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
spinner.setAdapter(spinnerArrayAdapter);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Select the Spinner element at index position 2
// It will select third element/item from Spinner
spinner.setSelection(2);
}
});
}
}
- How to use Spinner onItemSelected
- How to change Spinner item background color
- How to add an item to Spinner dynamically
- How to remove an item from Spinner programmatically
- How to find an item from Spinner
- How to set Spinner alternate item color
- How to set prompt text in a Spinner
- How to get Spinner selected item text
- How to hide an item from Spinner
- How to add a hint to Spinner