【问题标题】:How to make a child view not clickable inside a clickable container如何使可点击容器内的子视图不可点击
【发布时间】:2021-01-13 00:25:02
【问题描述】:
我有一个如下所述的布局容器:
<ConstraintLayout
android:id="@+id/container"
...>
<child1/>
<child2/>
<child3/>
</ConstraintLayout>
在我的代码中,我必须在容器上附加一个点击监听器,以便能够在用户点击容器的任何区域时执行操作。
从这个约束中排除 child2 的最佳解决方案是什么?我的意思是,所有容器区域都应该是可点击的,但 child2 不应该。
提前谢谢你
【问题讨论】:
标签:
android
android-layout
onclicklistener
【解决方案1】:
尝试了以下方法,它有效,只是一种解决方法,它可能不是最佳解决方案
activity_main.xml
<ConstraintLayout
android:id="@+id/container"
android:onClick = "doSomething"
...>
<child1/>
<child2
android:onClick="doNothing"/>
<child3/>
</ConstraintLayout>
活动类
//all but child2 responds to the clickevent
fun doNothing(view: View) {
//does nothing,empty function
}
fun doSomething(view: View) {
Toast.makeText(this, "did something", Toast.LENGTH_SHORT).show()
}
【解决方案2】:
尝试设置
android:clickable="false"
android:focusable="false"
为儿童。然后他们不会对点击做出反应。