// set spinner
spinner = (Spinner) findViewById(R.id.spinner_meterPointType);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.meterType_array, android.R.layout.simple_spinner_item); // the source is in strings.xml
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
// event fire when user select a item from spinner list
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
// set select value (set index of the value)
spinner.setSelection(indexInArray ,true);
// set select value (get select value index in array)
spinner.getSelectedItemPosition();
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
label_type.setText(parent.getItemAtPosition(pos).toString());
meterPointNum.setText("");
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
// if the spinner set the touch listener, the OnItemSelectedListener will not be used.
private View.OnTouchListener Spinner_OnTouch = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
return true;
}
};
strings.xml
<string name="name">Choose the value(spinner title)</string>
<string-array name="meterType_array"> // the array name is used in ArrayAdapter
<item>Electricity</item>
<item>Gas</item>
</string-array>