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>
Here is an workaround: Spinner spinner = (Spinner) findViewById(R. id. spinner); ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With