Last active
November 29, 2024 12:09
-
-
Save hector6872/3202a31660b0980ffc3069ac791114dd to your computer and use it in GitHub Desktop.
ClearableAutoCompleteTextView Kotlin
This file contains hidden or 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
class ClearableAutoCompleteTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, | |
defStyleAttr: Int = android.R.attr.editTextStyle) | |
: AutoCompleteTextView(context, attrs, defStyleAttr) { | |
private val clearDrawable: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_clear) | |
init { | |
clearDrawable?.setBounds(0, 0, clearDrawable.intrinsicWidth, clearDrawable.intrinsicHeight) | |
setOnTouchListener { _, event -> | |
if (isClearDrawableVisible() && event.action == MotionEvent.ACTION_UP) { | |
val clearDrawableClicked = event.x > width - paddingRight - (clearDrawable?.intrinsicWidth ?: 0) | |
if (clearDrawableClicked) { | |
setText("") | |
return@setOnTouchListener true | |
} | |
} | |
return@setOnTouchListener false | |
} | |
textWatcher { onTextChanged { text, _, _, _ -> setClearDrawableVisibility(!text.isNullOrEmpty()) } } | |
} | |
private fun isClearDrawableVisible(): Boolean { | |
return compoundDrawables[2] != null | |
} | |
private fun setClearDrawableVisibility(visible: Boolean) { | |
setCompoundDrawables(compoundDrawables[0], compoundDrawables[1], if (visible) clearDrawable else null, | |
compoundDrawables[3]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://gist.github.com/hector6872/58d64be39128edf41527ed79a75e7108