Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adapter for spinner with hint
/**
* @author Vasili Chyrvon (vasili.chyrvon@gmail.com)
*/
class SpinnerWithHintAdapter(context: Context, @LayoutRes resource: Int, @StringRes hintResId: Int) : ArrayAdapter<String>(context, resource) {
private val hintColor by lazy { getHintColorAttribute() }
private var textColors: ColorStateList? = null
private val hint by lazy { context.getString(hintResId) }
override fun isEnabled(position: Int): Boolean {
return if (position == 0) false else super.isEnabled(position)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
val text = super.getDropDownView(position, convertView, parent) as TextView
if (textColors == null) textColors = text.textColors // Save default text
if (position == 0) text.setTextColor(hintColor) else text.setTextColor(textColors)
return text
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val text = super.getView(position, convertView, parent) as TextView
if (position == 0) text.setTextColor(hintColor)
return text
}
override fun add(`object`: String?) {
super.add(`object`)
if (noHint()) insert(hint, 0)
}
override fun addAll(collection: MutableCollection<out String>?) {
super.addAll(collection)
if (noHint()) insert(hint, 0)
}
override fun addAll(vararg items: String?) {
super.addAll(*items)
if (noHint()) insert(hint, 0)
}
private fun noHint() = count == 0 || getItem(0) != hint
override fun clear() {
super.clear()
add(hint)
}
private fun getHintColorAttribute(): Int {
val tv = TypedValue()
context.theme.resolveAttribute(android.R.attr.textColorHint, tv, true)
return ContextCompat.getColor(context, tv.resourceId)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment