Friday, April 11, 2014

Spinner with different display text and return value

In the most basic Spinner implementation, selected item can be retrieved by calling parent.getItemAtPosition(position) in onItemSelected() method in OnItemSelectedListener. It will be the same object of the display items, as show in the spinner0 of the example.

Sometimes, we want to display some meaningful text in Spinner (such as "Sunday", "Monday"...), but return some other value when any item selected (such as 0, 2...).

Spinner with different display text and return value
Here I show two approaches:
  • The first one may be the simplest method, spinner1 in the example. Create another array to hold the values we want to return. And return the coresponding item on position in onItemSelected().
  • The second approach implement our custom class to hold the display text and the return value. And implement our custom Adapter, as shown in spinner2 in the example.

package com.example.androidspinnertext;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 String[] text0 = { "Sunday", "Monday", "Tuesday", 
   "Wednesday", "Thursday", "Friday", "Saturday" };
 
 String[] text1 = { "SUNDAY", "MONDAY", "TUESDAY", 
   "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" };
 int[] val1 = { 0, 1, 2, 3, 4, 5, 6};
 
 MyClass[] obj2 ={
  new MyClass("SUN", 0),
  new MyClass("MON", 1),
  new MyClass("TUE", 2),
  new MyClass("WED", 3),
  new MyClass("THU", 4),
  new MyClass("FRI", 5),
  new MyClass("SAT", 6)
 };
 
 Spinner spinner0, spinner1, spinner2;
 TextView textView0, textView1, textView2;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  textView0 = (TextView)findViewById(R.id.text0);
  spinner0 = (Spinner)findViewById(R.id.spinner0);
  ArrayAdapter<String> adapter0 = 
   new ArrayAdapter<String>(MainActivity.this, 
     android.R.layout.simple_spinner_item, text0);
  adapter0.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spinner0.setAdapter(adapter0);
  spinner0.setOnItemSelectedListener(onItemSelectedListener0);
  
  textView1 = (TextView)findViewById(R.id.text1);
  spinner1 = (Spinner)findViewById(R.id.spinner1);
  ArrayAdapter<String> adapter1 = 
   new ArrayAdapter<String>(MainActivity.this, 
     android.R.layout.simple_spinner_item, text1);
  adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spinner1.setAdapter(adapter1);
  spinner1.setOnItemSelectedListener(onItemSelectedListener1);
  
  textView2 = (TextView)findViewById(R.id.text2);
  spinner2 = (Spinner)findViewById(R.id.spinner2);
  MySpinnerAdapter adapter2 = 
   new MySpinnerAdapter(MainActivity.this, 
     android.R.layout.simple_spinner_item, obj2);
  //adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spinner2.setAdapter(adapter2);
  spinner2.setOnItemSelectedListener(onItemSelectedListener2);

 }
 
 OnItemSelectedListener onItemSelectedListener0 =
  new OnItemSelectedListener(){

   @Override
   public void onItemSelected(AdapterView<?> parent, View view,
     int position, long id) {
    String s0 = (String)parent.getItemAtPosition(position);
    textView0.setText(s0);
   }

   @Override
   public void onNothingSelected(AdapterView<?> parent) {}
 };
 
 OnItemSelectedListener onItemSelectedListener1 =
  new OnItemSelectedListener(){

   @Override
   public void onItemSelected(AdapterView<?> parent, View view,
     int position, long id) {
    String s1 = String.valueOf(val1[position]);
    textView1.setText(s1);
   }

   @Override
   public void onNothingSelected(AdapterView<?> parent) {}

 };
 
 OnItemSelectedListener onItemSelectedListener2 =
  new OnItemSelectedListener(){

   @Override
   public void onItemSelected(AdapterView<?> parent, View view,
     int position, long id) {
    MyClass obj = (MyClass)(parent.getItemAtPosition(position));
    textView2.setText(String.valueOf(obj.getValue()));
   }

   @Override
   public void onNothingSelected(AdapterView<?> parent) {}

 };
 
 //define our custom class
 public class MyClass{

  private String text;
     private int value;
     

     public MyClass(String text, int value){
      this.text = text;
      this.value = value;
     }
     
     public void setText(String text){
         this.text = text;
     }

     public String getText(){
         return this.text;
     }

     public void setValue(int value){
         this.value = value;
     }

     public int getValue(){
         return this.value;
     }
 }
 
 //custom adapter
 public class MySpinnerAdapter extends ArrayAdapter<MyClass>{

     private Context context;
     private MyClass[] myObjs;

     public MySpinnerAdapter(Context context, int textViewResourceId,
       MyClass[] myObjs) {
         super(context, textViewResourceId, myObjs);
         this.context = context;
         this.myObjs = myObjs;
     }

     public int getCount(){
        return myObjs.length;
     }

     public MyClass getItem(int position){
        return myObjs[position];
     }

     public long getItemId(int position){
        return position;
     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
         TextView label = new TextView(context);
         label.setText(myObjs[position].getText());
         return label;
     }

     @Override
     public View getDropDownView(int position, View convertView,
             ViewGroup parent) {
         TextView label = new TextView(context);
         label.setText(myObjs[position].getText());
         return label;
     }
 }

}

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidspinnertext.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <Spinner
        android:id="@+id/spinner0"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text0"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    
</LinearLayout>



download filesDownload the files.

7 comments:

  1. Description Resource Path Location Type
    error: Error retrieving parent for item: No resource found that matches the given name 'Theme.AppCompat.Light'. styles.xml /AndroidSpinnerText/res/values line 7 Android AAPT Problem

    ReplyDelete
  2. thanks good yr......

    ReplyDelete
  3. Can we not use a Map instead of MyClass?

    ReplyDelete
  4. this tutorial is great thanks

    ReplyDelete
  5. Not finding the resource files in the code.
    Could you pls publish them as well

    ReplyDelete