Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible to create a spinner with images instead of text?

Tags:

Given the code bellow, is it possible to have images instead of text in the array planets?

    Spinner s = (Spinner) findViewById(R.id.spinner);         ArrayAdapter adapter = ArrayAdapter.createFromResource(                         this, R.array.planets, android.R.layout.simple_spinner_item);         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);         s.setAdapter(adapter); 

and

    <string name="planet_prompt">Choose a planet</string>     <string-array name="planets">                 <item>Mercury</item>         <item>Venus</item>         <item>Earth</item>                 <item>Mars</item>                 <item>Jupiter</item>                 <item>Saturn</item>                 <item>Uranus</item>                 <item>Neptune</item>         </string-array>     
like image 856
thpoul Avatar asked Aug 31 '10 12:08

thpoul


People also ask

How can I make my spinner look like Edittext?

Here is an workaround: Spinner spinner = (Spinner) findViewById(R. id. spinner); ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.


1 Answers

I just needed a super easy solution for a fixed set of images in a spinner, so I did this:

public class SimpleImageArrayAdapter extends ArrayAdapter<Integer> { private Integer[] images;  public SimpleImageArrayAdapter(Context context, Integer[] images) {     super(context, android.R.layout.simple_spinner_item, images);     this.images = images; }  @Override public View getDropDownView(int position, View convertView, ViewGroup parent) {     return getImageForPosition(position); }  @Override public View getView(int position, View convertView, ViewGroup parent) {     return getImageForPosition(position); }  private View getImageForPosition(int position) {         ImageView imageView = new ImageView(getContext());         imageView.setBackgroundResource(images[position]);         imageView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));         return imageView; } 

}

And then in the code you can just use it like this:

    SimpleImageArrayAdapter adapter = new SimpleImageArrayAdapter(context,          new Integer[]{R.drawable.smiley1, R.drawable.smiley2, R.drawable.smiley3, R.drawable.smiley4, R.drawable.smiley5});     spinner.setAdapter(adapter); 
like image 83
koljaTM Avatar answered Mar 06 '23 06:03

koljaTM