EditText inside TextInputLayout onclick requires 2 click ?! Android

前端 未结 2 1233
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 18:30

I am simply trying to have an onlick listen on an Edit text inside a TextInputLayout. It works but I need to click on the EditText twice for it to trigger I dont understand why.

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-01 19:00

    I found an alternative solution which suited my needs better than the other answer. Basically you set the onClickListener as normal, but you add an OnFocusChangedListener to pick up the first tap (when gaining focus). This only activates in touch mode so doesn't affect keyboard navigation.

    You don't need to set any XML attributes related to focus, just use the following code (it's kotlin btw):

        editText.setOnFocusChangeListener { view, isFocused ->
            if (view.isInTouchMode && isFocused) {
                view.performClick()  // picks up first tap
            }
        }
        editText.setOnClickListener {
            showDatePicker() // the actual thing you want to do
        }
    

    This method has the advantage that the view will remain focused (and if you are using a TextInputLayout.OutlinedBox style, it will remain highlighted) even after the DatePicker is dismissed. This does not happen when you set focusableInTouchMode = false.

    Once the view is focused, future taps will trigger only the OnClickListener, so it won't be called again by the FocusChangeListener calling performClick(). (I checked this with the debugger on API 29)

提交回复
热议问题