If anyone is looking for a Kotlin Answer, here is how you do it.
class DynamicSizeSpinner : androidx.appcompat.widget.AppCompatSpinner {
var inOnMeasure = false
private set
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
inOnMeasure = true
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
inOnMeasure = false
}
}
class SpinnerArrayAdapter(context: Context,@LayoutRes layout: Int, val entries: List<String>) : ArrayAdapter<String>(context, layout, entries) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val selectedItemPosition = when (parent) {
is AdapterView<*> -> parent.selectedItemPosition
is DynamicSizeSpinner -> parent.selectedItemPosition
else -> position
}
return makeLayout(selectedItemPosition, convertView, parent, R.layout.simple_spinner_dropdown_item_custom)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
return makeLayout(position, convertView, parent, R.layout.simple_spinner_dropdown_item_custom)
}
private fun makeLayout(position: Int, convertView: View?, parent: ViewGroup, layout: Int): View {
val view = convertView ?: LayoutInflater.from(context).inflate(layout, parent, false)
if (position != -1) {
(view as? TextView)?.text = entries[position]
}
return view
}
}
Use the DynamicSizeSpinner
as you would use the default Spinner
in your XML/JAVA/Kotlin code.
P.S don't forget to read the original article.
inOnMeasure
in yourDynamicSizeSpinner
, the field is not used bySpinnerArrayAdapter
– Vashti