Tuesday, August 28, 2012

Android | Spinner Example

When we have multiple values and out of them we need to select one item then we can use Spinner UI component.

Populating Spinner is little bit different. I would like to guide you that there are two sources from which we can populate spinner (1) Array and (2) database.

Adapter is playing key role between UI component and data sources.

Note: below example verified on Android 4.0.3 emulator.

activity_spinner_example.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   
    <Spinner
        android:id="@+id/spnrcountries"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />


</LinearLayout>


Strings.xml


<resources>

    <string name="app_name">SpinnerExample</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_spinner_example">Spinner Example</string>
   
   
</resources>

SpinnerExample.java



package com.example.spinnerexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class SpinnerExample extends Activity  {

private Spinner spnrCountries;
private String[] strCountries = {"US","UK","Spain","Germany","Italy","India","China"};

private ArrayAdapter<String> oArrayAdapter ;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_example);
       

        spnrCountries = (Spinner) findViewById(R.id.spnrcountries);
       

        oArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, strCountries);
        spnrCountries.setAdapter(oArrayAdapter);
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_spinner_example, menu);
        return true;
    }


}


Result:




No comments:

Post a Comment