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

Viewed 37738

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>    
4 Answers

Not sure if anyone is still using Spinners in 2020, but here's a Kotlin version of this solution (https://stackoverflow.com/a/22216375/6007104):

class MySpinnerAdapter(context: Context, images: Array<Int>) :
    ArrayAdapter<Int>(context, android.R.layout.simple_spinner_item, images) {

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup) =
        getImageForPosition(position)

    override fun getView(position: Int, convertView: View?, parent: ViewGroup) =
        getImageForPosition(position)

    private fun getImageForPosition(position: Int) = ImageView(context).apply {
        setBackgroundResource(getItem(position)!!)
        layoutParams = ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
    }
}

The above solution using SimpleImageArrayAdapter works perfectly except when the Android version is Marshmallow or older in which case you have to use an ArrayAdapter with a string-array like that specified in the original question otherwise your dropdown list will be an empty white box.

Related