Spinner for Dropdown

Spinner helps you to display the set of data (collection). It allows teh data to be displayed in drop down fashion.
Example:
1. Lets define a static String array in Android XML file.


<?xml version="1.0" encoding="utf-8"?>
<resources> <string-array name="countries"> <item>India</item> <item>U.A.E.</item> <item>Nepal</item> <item>China</item> <item>Australia</item> <item>United States</item> <item>Europe</item> <item>United Kingdom</item> <item>Australia</item> <item>Canada</item> <item>Japan</item> <item>Singapore</item> </string-array> </resources>

2. Configure Spinner in your activity XML file.     

<Spinner    
android:id="@+id/location_spinner"    
android:layout_width="wrap_content"    
android:layout_height="wrap_content"
android:background="@android:drawable/btn_dropdown"
android:spinnerMode="dropdown"    />





background attribute is used to define background for the Spinner. If not specified, the spinner will not be a defined background else if specified, will appear as below-                          


With background
without Background


spinnerMode attribute is used to control the fashion in which the dataset should be displayed. That is, dropdown or dialog. In case of 'dropdown', the values will be shown in dropdown fashion and in case of 'dialog', the values will be shown in a dialog box [values are not shown as attached items to the field holder (spinner)],

attribute = 'dialog'
attribute='dropdown'



3. Configuring the Spinner in Java

private void initialiseLocationSpinner() {
    Spinner dropdownSpinner = (Spinner)findViewById(R.id.location_spinner);

    // Spinner element
    String[] items = getResources().getStringArray(R.array.countries);

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);

    // Drop down layout style
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner    
    dropdownSpinner.setAdapter(dataAdapter);

   // Spinner click listener
    dropdownSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // On selecting a spinner item
                String item = parent.getItemAtPosition(position).toString();

                // Showing selected spinner item
                Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
        }

Comments

Popular posts from this blog

@Overrride annotation introduced in Java1.5

Liskov Substitution Principle (LSP)

Marie Choco Lava