简体   繁体   English

当子视图有点击监听器时,父视图上的 OnTouchListener 不会被调用

[英]OnTouchListener on parent view is not getting called when there is a click listener for child views

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/actions"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/action_previous"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/action_next"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintHorizontal_weight="3"/>

    <View
        android:id="@+id/action_next"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/action_previous"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintHorizontal_weight="7"/>

</androidx.constraintlayout.widget.ConstraintLayout>

ImageActivity.kt图像活动.kt

swipe_parent.setOnTouchListener { v, event ->
  Toast.makeText(this@ImageActivity, "OnTouch called $v, $event", Toast.LENGTH_SHORT).show()
  return@setOnTouchListener true
}

action_previous.setOnClickListener {
  Toast.makeText(this, "Previous", Toast.LENGTH_SHORT).show()
}

action_next.setOnClickListener {
  Toast.makeText(this, "Next", Toast.LENGTH_SHORT).show()
}

I read in many comments stating if there is a onClickListener for child view then OnTouchListener call won't be passed to the parent (If the views are structured as above).我在许多评论中读到,如果子视图有 onClickListener,则不会将 OnTouchListener 调用传递给父视图(如果视图的结构如上)。 And logically it makes sense as well, as it would be hard to differentiate between the clicks and touch.从逻辑上讲,这也是有道理的,因为很难区分点击和触摸。

If this is my requirement, how do I achieve this?如果这是我的要求,我该如何实现?

Fastest way to resolve this problem would be using ontouch instead of onclick, but mimic the onclick functionality, inside the child view ontouch check this condition, it is only executed for action_down case only which would be helpful in your case.解决此问题的最快方法是使用 ontouch 而不是 onclick,但模仿 onclick 功能,在子视图 ontouch 中检查此条件,它仅针对 action_down 情况执行,这对您的情况有帮助。

if (event.action == MotionEvent.ACTION_DOWN)

I faced the same problem.我遇到了同样的问题。 I resolved it by setting我通过设置解决了

android:clickable="false"
android:descendantFocusability="blocksDescendants"

in the parent view.在父视图中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM