Tuesday, February 12, 2013

Spinner and ArrayAdapter

This one is simplest possible tutorial, but I need Spinner to allow user to set time interval and frequency for countdown timer. So lets explain it, maybe somebody doesn’t know how to use it.
Spinner is control which corresponds to drop-down, like HTML select or Java/Swing JComboBox. When user selects it, it expands, pops-up list view where selection could be made. After selection is made list view disappears and selected item’s value is on collapsed control. Data binding and selection events are handled by ArrayAdapter and AdapterView. In Android SDK is example how to load ArrayAdapter from resource and I will load it from array of strings. Here is complete code:

public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
    private static final String[] items={"5", "10", "15", "20", "30"};
    private ArrayAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner spinner=(Spinner)findViewById(R.id.spinner1);
        spinner.setOnItemSelectedListener(this);
        adapter=new ArrayAdapter(this, android.R.layout.simple_spinner_item, items);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setSelection(0);
    }
    @Override
    public void onItemSelected(AdapterView parent, View view, int position, long id) {
        Toast.makeText(this, adapter.getItem(position) + " is selected", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onNothingSelected(AdapterView parent) {
        Toast.makeText(this, "Nothing selected", Toast.LENGTH_SHORT).show();
    }
}


Add to default imports AdapterView, ArrayAdapter, Spinner and Toast. In layout, activity_main.xml I placed one Spinner and accepted default name for it. AdapterView.OnItemSelectedListener is used to implement listeners inside activity and again do it differently from SDK example. Difference between android.R.layout.simple_spinner_dropdown_item and android.R.layout.simple_spinner_item is that first one will give you nicer user interface with radio button. To ArrayAdapter constructor we must pass array of strings, array of integers won’t work. Before we show UI we set selected item to position 0. Selecting different items will demonstrate how listener works.

No comments:

Post a Comment