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

前端 未结 3 1020
遥遥无期
遥遥无期 2020-12-07 23:12

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

    Spinner s = (Spinner) findViewById(R.id.spinner);    
    Arra         


        
3条回答
  •  半阙折子戏
    2020-12-07 23:53

    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) :
        ArrayAdapter(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)
        }
    }
    

提交回复
热议问题