Kotlin : Click event for Android EditText Left Drawable

Viewed 161

The following code is for click on Right side, what sould I change to Clickon EditText on Left Drawable ?

fun EditText.onRightDrawableClicked(onClicked: (view: EditText) -> Unit) {
        this.setOnTouchListener { v, event ->
            var hasConsumed = false
            if (v is EditText) {
                if (event.x >= v.width - v.totalPaddingRight) {
                    if (event.action == MotionEvent.ACTION_UP) {
                        onClicked(this)
                    }
                    hasConsumed = true
                }
            }

            hasConsumed
        }
    }
2 Answers

You should change this event.x >= v.width - v.totalPaddingRight to event.x <= v.totalPaddingLeft . If it's still lacking, you can always plus the size of your drawable

You should use drawable bounds like this

setOnTouchListener { v, event ->
            if (event.action == MotionEvent.ACTION_DOWN) {
                if ((event.rawX + paddingRight )>= (right - (compoundDrawables.getOrNull(DRAWABLE_RIGHT)?.bounds?.width()
                        ?: 0))
                ) {
                   // right drawable clicked
                } else if (event.rawX - paddingLeft <= ((compoundDrawables.getOrNull(DRAWABLE_LEFT)?.bounds?.width()
                        ?: 0) + left)
                ) {
                    // left drawable clicked
                }
            }
            false
        }
Related