TextView的属性textIsSelectable=true设置后需要第二次点击才响应事件问题解决记录
- 在为TextView设置textIsSelectable=true属性后,同时又加了setOnClickListener监听,之后发现只有在第二次点击时才能响应OnClickListener
- 那么解决办法就是在事件处理中发现单击的话就通过callOnClick()触发响应监听,其他情况就把事件抛给父类处理即可
import android.annotation.SuppressLint;
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.appcompat.widget.AppCompatTextView
class SelectableFixedTextView : AppCompatTextView {
private var mLastActionDownTime = 0L
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
var handle = false
when (event.action) {
MotionEvent.ACTION_DOWN -> mLastActionDownTime = System.currentTimeMillis()
MotionEvent.ACTION_UP -> {
val actionUpTime = System.currentTimeMillis()
handle =
if (actionUpTime - mLastActionDownTime < ViewConfiguration.getLongPressTimeout()) {
callOnClick()
true
} else {
false
}
}
}
return if (!handle ) {
super.onTouchEvent(event)
} else {
false
}
}
}
参考