activity_main.xml
<Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/textView" android:layout_toEndOf="@+id/textView" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" android:id="@+id/spinnerCountries" />
Spinner spinner; ArrayAdapter<String> spinnerAdapter; String[] countries; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinner= (Spinner) findViewById(R.id.spinnerCountries); countries=getResources().getStringArray(R.array.countries); spinnerAdapter=new ArrayAdapter(this,android.R.layout.simple_spinner_item,countries); spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(spinnerAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Toast toast=Toast.makeText(getBaseContext(),parent.getSelectedItem().toString(),Toast.LENGTH_LONG); toast.show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); }
References
https://github.com/mhdr/AndroidSamples/tree/master/011