Saturday, 25 December 2010

Custom ArrayAdapter for Spinner, with different icons

In last exercise "Custom Spinner with icon", a custom spinner have been implemented. But all row have the same icon. In order to display a spinner with difference icons on each row, we can implement our own ArrayAdapter, override getDropDownView() and getView() methods.

Custom ArrayAdapter for Spinner, with different icons

row.xml and main.xml keep no change as in the exercise "Custom Spinner with icon".

AndroidCustomSpinner.java
package com.exercise.AndroidCustomSpinner;

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

public class AndroidCustomSpinner extends Activity {

String[] DayOfWeek = {"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
mySpinner.setAdapter(new MyCustomAdapter(AndroidCustomSpinner.this, R.layout.row, DayOfWeek));
}

public class MyCustomAdapter extends ArrayAdapter<String>{

public MyCustomAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
}

@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
return getCustomView(position, convertView, parent);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return getCustomView(position, convertView, parent);
}

public View getCustomView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);

LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
TextView label=(TextView)row.findViewById(R.id.weekofday);
label.setText(DayOfWeek[position]);

ImageView icon=(ImageView)row.findViewById(R.id.icon);

if (DayOfWeek[position]=="Sunday"){
icon.setImageResource(R.drawable.icon);
}
else{
icon.setImageResource(R.drawable.icongray);
}

return row;
}
}
}
***********
It's a programmatic pitfall here:
in getCustomView(), Condition checking of String ("Sunday") should be checked with:
(DayOfWeek[position].equals("Sunday"))

"==" not always work! refer String Comparison: equals()? ==?
***********


Download the files.

* Please see the article "In-correct arrow icon on Spinner with custom ArrayAdapter"!

No comments:

Post a Comment