fredag 23 mars 2012

Android : Using a Spinner with custom object



Spinners is really easy to work with if you just need to display your object with it's toString() function.

First a simple layout: 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button android:id="@+id/buttonPopulate"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Simple Spinner with custom data" />
    <Spinner  android:id="@+id/mySpinner"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"/>
    <Button android:id="@+id/buttonUseItem"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Use Selection"/>
    <TextView android:id="@+id/myTextView"
              android:layout_height="wrap_content"
              android:layout_width="wrap_content"/>
</LinearLayout>

Next up, a simple class to populate our Spinner with!

public class CountryInfo {
    private String countryName;
    private long countryPopulation;
    
    public CountryInfo(String cName, long cPopulation)
    {
        countryName = cName;
        countryPopulation = cPopulation;
    }
    
    public String getCountryName()
    {
        return countryName;
    }

    public long getCountryPopulation()
    {
        return countryPopulation;
    }

    public String toString()
    {
        return countryName;
    }
}

No odd behavior here, and last our SpinnerTest class
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import java.util.ArrayList;

public class SpinnerTest extends Activity
{
    
    Button button_UseSelectedItem;
    Spinner mySpinner;
    TextView myTextView;
    ArrayList<CountryInfo> myCountries;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        myCountries = populateList();
        setContentView(R.layout.main);
        mySpinner = (Spinner) findViewById(R.id.mySpinner);
        button_UseSelectedItem = (Button) findViewById(R.id.buttonUseItem);
        myTextView = (TextView) findViewById(R.id.myTextView);
        
        ArrayAdapter<CountryInfo> myAdapter = new ArrayAdapter<CountryInfo>(this, android.R.layout.simple_spinner_item, myCountries);
        mySpinner.setAdapter(myAdapter);
        
        button_UseSelectedItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Can also use mySpinner.setOnItemClickListener(......) 
                // Using a separate button here as there's often other data to select
                // or if you choose the wrong item.
                CountryInfo myCountry;
                if(!(mySpinner.getSelectedItem() == null))
                {
                    myCountry = (CountryInfo) mySpinner.getSelectedItem();
                    myTextView.setText(String.format("Country: " + myCountry.getCountryName() + "\t Population: " + myCountry.getCountryPopulation()))
            }
        });
    }

    public ArrayList<CountryInfo> populateList()
    {
        ArrayList<CountryInfo> myCountries = new ArrayList<CountryInfo>();
        myCountries.add(new CountryInfo("USA", 308745538));
        myCountries.add(new CountryInfo("Sweden", 9482855));
        myCountries.add(new CountryInfo("Canada", 34018000));
        return myCountries;
    }
}

Simple! Just using the internal android.R.layout.simple_spinner_item layout, remember to create a toString() for your custom object.

Link to source for android.R.layout_simple_spinner_item



I'll add another post later for customizing your spinner and adapter.

5 kommentarer:

  1. if i have two fields in object , how to get the particular field to spinner .

    guess i have full name , dob , gender in a array list of objects . how to get only the full name on spinner .

    SvaraRadera
    Svar
    1. Hi,
      If you use android.R.layout.simple_spinner_item as the layout in the spinner it'll use your objects toString() method as the text, so just override it to display the correct text.

      Radera
  2. When I allow the user to edit his dropdown list value, how should I display the previously selected option in the Spiner?

    SvaraRadera
  3. Hola hermano, muchas gracias, no sabia que se podia llenar de esa forma, sin necesidad de hacer una clase aparte para el adaptador... mil gracias saludos

    SvaraRadera