Что вы можете просто сделать, это создать текст редактирования с android: drawableRight = R.drawable.close внутри вашего editText
<EditText
.....
android:drawableRight = R.drawable.close
.....
/>
и затем присоединить к нему этих слушателей
open class SimpleWatcher(val inputLayout: TextInputLayout,
val context: Context?,
val editText: EditText,val shouldShowCloseButton:Boolean = true): TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if(s?.isNotEmpty() == true){
if(shouldShowCloseButton) {
context?.let {
//This is the important one. Sets back the drawable after removing it when the text is empty
editText.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(it, R.drawable.ic_edit_text_close), null)
}
}
inputLayout.error = null
}else{
if(shouldShowCloseButton) {
editText.setCompoundDrawables(null, null, null, null)
}
}
}
}
class EditTextOnTouchListener(val view: EditText): View.OnTouchListener{
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
val DRAWABLE_RIGHT = 2
if(event?.action == MotionEvent.ACTION_UP){
if(view.compoundDrawables[DRAWABLE_RIGHT] != null) {
if (event.rawX >= (view.right -
view.compoundDrawables[DRAWABLE_RIGHT].bounds.width())) {
// Toast.makeText(context, "Close Clicked",
Toast.LENGTH_SHORT).show()
view.text = Editable.Factory.getInstance().newEditable("")
view.clearFocus()
return true
}
}
}
return false
}
}
Бери то, что нужно, и игнорируй все остальное.в основном тело внутри onTextChanged и EditTextOnTouchListener.Поскольку это работает с сенсорным слушателем, каждый раз, когда приходит касание, слушатель будет вызван и будут предприняты соответствующие действия