Wednesday, June 29, 2011

Android: DropDown for Images using spinner

 What is spinner?
        Spinner is a widget similar to a drop-down list for selecting items.

Usage of spinner tag to create a drop-down list with image?

SpinnerSample.xml :

    <Spinner android:id="@+id/spinner_img"
        android:layout_height="35dip" android:layout_weight="15"
        android:clipToPadding="true" />

spinner_op.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content">
    <ImageView android:id="@+id/icon" android:layout_height="wrap_content"
        android:src="@drawable/icon" android:layout_width="fill_parent">
    </ImageView>
</LinearLayout>

SpinnerImgActivity class:

        Spinner spinner = (Spinner) findViewById(R.id.spinner_img);

        Integer[] image = { R.drawable.img1, R.drawable.img2, R.drawable.img3 };
        spinner.getLayoutParams().width = 3;

        // Customise ArrayAdapter
        spinner.setAdapter(new SpinnerImgAdapter(Success.this, R.layout.spinner_op, image));

SpinnerImgAdapter java class  // Customized

public class SpinnerImgAdapter extends ArrayAdapter<Integer>
{

    private final Activity context;

    private final Integer[] names;

    public SpinnerImgAdapter(Activity context, int textViewResourceId, Integer[] objects)
    {
        super(context, R.layout.spinner_op, objects);
        this.context = context;
        this.names = objects;
    }

    static class ViewHolder
    {
        public ImageView imageView;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent)
    {
        return getImageView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {

        return getImageView(position, convertView, parent);
    }

    private View getImageView(int position, View convertView, ViewGroup parent)
    {
        ViewHolder holder;

        View rowView = convertView;

        if (rowView == null)
        {
            LayoutInflater inflater = context.getLayoutInflater();
            rowView = inflater.inflate(R.layout.spinner_op, null, true);
            holder = new ViewHolder();
            holder.imageView = (ImageView) rowView.findViewById(R.id.icon);
            rowView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) rowView.getTag();
        }
      
        Integer integer = names[position];

        holder.imageView.setImageResource(integer);
      
        return rowView;
    }
}

run the application :)

2 comments :