Following example demonstrates Spinner Class demo and displays the dropdown list of days.
File Name: strings.xml
<resources>
<string name = "app_name">SpinnerDemo</string>
<string name = "action_settings">Settings</string>
<string-array name = "Days">
<item>Sunday</item>
<item>Monday</item>
<item>Tuesday</item>
<item>Wednesday</item>
<item>Thursday</item>
<item>Friday</item>
<item>Saturday</item>
</string-array>
</resources>
File Name: content_main.xml
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayoutxmlns: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"
android:paddingBottom = "@dimen/activity_vertical_margin"
android:paddingLeft = "@dimen/activity_horizontal_margin"
android:paddingRight = "@dimen/activity_horizontal_margin"
android:paddingTop = "@dimen/activity_vertical_margin"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"
tools:context = "com.example.custom.spinnerdemo.MainActivity"
tools:showIn = "@layout/activity_main">
<Spinner
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/spinner"
android:layout_alignParentTop = "true"
android:layout_alignParentLeft = "true"
android:layout_alignParentStart = "true" />
</RelativeLayout>
File Name: MainActivity.java
public class MainActivity extends AppCompatActivity
{
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
R.array.Days, android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected (AdapterView> parent, View view, intposition, long id)
{
TextView txt = (TextView)view;
Toast toast = Toast.makeText(getApplicationContext(), "Selected day ="+txt.getText(), Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}
@Override
public void onNothingSelected (AdapterView parent)
{
}
});
}
}