Skip to content

Instantly share code, notes, and snippets.

@hector6872
Last active November 29, 2024 12:09
Show Gist options
  • Save hector6872/3202a31660b0980ffc3069ac791114dd to your computer and use it in GitHub Desktop.
Save hector6872/3202a31660b0980ffc3069ac791114dd to your computer and use it in GitHub Desktop.
ClearableAutoCompleteTextView Kotlin
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])
}
}
@hector6872
Copy link
Author

hector6872 commented Jan 16, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment