Spinners provide a way to select one value from a set. The spinner displays a dropdown menu with all available values, from which the user can select a new one. In the default state, a spinner shows its currently selected value.
To add a list of values to the spinner, you then need to specify a SpinnerAdapter in your Activity, which extends Adapter class.. A spinner adapter allows to define two different views: one that shows the data in the spinner itself and one that shows the data in the drop down list when the spinner is pressed.
Here is a complete example that shows the usage of spinner.
activity_main.xml
<RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:background=“@drawable/bg_cyan”
android:gravity=“center”>
<Spinner
android:id=“@+id/spinner_id”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content” />
</RelativeLayout>
MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class MainActivity extends Activity {
Spinner spin;
String spin_val;
String[] gender = { “Male”, “Female” };//array of strings used to populate the spinner
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//setting layout
spin = (Spinner) findViewById(R.id.spinner_id);//fetching view’s id
//Register a callback to be invoked when an item in this AdapterView has been selected
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
spin_val = gender[position];//saving the value selected
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
//setting array adaptors to spinners
//ArrayAdapter is a BaseAdapter that is backed by an array of arbitrary objects
ArrayAdapter<String> spin_adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, gender);
// setting adapter to spinner
spin.setAdapter(spin_adapter);
}
}
I’m also attaching my spinner_Demo project for your reference. spinner_DEMO 🙂
Screenshots: