Created
June 20, 2017 14:47
-
-
Save Jeevuz/0e03f690f6c57543fd4c2d7a51c2fcf3 to your computer and use it in GitHub Desktop.
Adapter for spinner with hint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Vasili Chyrvon ([email protected]) | |
*/ | |
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