<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="82dp"
android:entries="@array/Sky_Colors" />
There is special tag :entries. This tag populates the spinner from array data items.
Data source may be populated either from Array defined in strings.xml(res/values folder) or array defined in the program.
For defining array in strings.xml, it can be added using add option in Android Resource screen. Then select Integer Array or String Array. Array Name should be mentioned. Then items should be added with suitable value. A sample string will have following entry:
<string-array name="Sky_Colors">
<item >Red</item>
<item >Blue</item>
<item >Green</item>
<item >Silver</item>
</string-array>
This array can be referenced from layout xml file in property :entries.
ArrayAdapter can be created using by strings arrary. For this createFromResource method is used.
ArrayAdapter<CharSequence> ab = ArrayAdapter.createFromResource(getApplicationContext(), R.array.Sky_Colors, android.R.layout.simple_spinner_item);
Arrayadapter may be created using program array. The syntax for this is as follows:
ArrayAdapter<String> aa= new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, names);
The R.layout.simple_spinner_item is the layout resource that defines how the selected choice will appear in the spinner control.
Once the ArrayAdapter is created, it can set as data adapter for the spinner using method setAdapter.
spin3.setAdapter(aa);
When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event and its interface implementation be specified by calling setOnItemSelectedListener()
To define the selection event handler for a spinner, implement the AdapterView.OnItemSelectedListener interface. This interface requires the onItemSelected() and onNothingSelected() callback methods
spin1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Item selected"+parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Nothing Selected", Toast.LENGTH_LONG).show();
}
Vijay Rastogi Mobility Consultant at Sisoft Technologies Indirapuram Ghaziabad