如何让点击事件通过子视图并到达其父级(并更改背景)

时间:2016-03-30 00:06:41

标签: android android-layout

整件事看起来像这样:

+---------+---------+
|   Mon   | 10:00AM |
+---------+---------+

这是一个带有两个TextView的LinearLayout。我希望点击事件通过“Mon”部分并在点击时更改LinearLayout的背景。 '10:00AM'仍然需要接受单独的点击事件。

XML:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal"
    android:background="@drawable/button_filled_white"
    android:clickable="true"
    >
    <TextView android:text="MON"
                 android:layout_width="0dp"
                 android:layout_height="match_parent"
                 android:layout_weight="1"
                 android:clickable="false"
                 android:enabled="false"
                 android:focusable="false"
        />
    <TextView android:text="10:00AM"
                 android:layout_width="0dp"
                 android:layout_height="match_parent"
                 android:layout_weight="1"
                 android:id="@+id/txtTime"
        />
</LinearLayout>

要让点击事件彻底“MON”TextView,我尝试将各种组合设置为可点击,可聚焦并启用为false但仍然,LinearLayout的背景不会改变。

如果删除子TextView,可以点击LinearLayout,点击后可以看到背景改变颜色:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal"
    android:background="@drawable/button_filled_white"
    android:clickable="true"
    />

我知道ViewGroup.onInterceptTouchEvent()但我正在寻找一种XML方式,因为处理ViewGroup.onInterceptTouchEvent()需要特定于情境和视图ID特定的实现。

2 个答案:

答案 0 :(得分:0)

您可以尝试设置

android:focusable="false"

到“星期一”子视图

答案 1 :(得分:0)

很抱歉回答我自己的问题,但为了帮助有相同问题的人,我会提供更多详情。

根本原因是NestedScrollView。

我实际上在NestedScrollView中合成了LinearLayout并且阻止了可点击的&amp; focusable = false正常工作。设置为true实际上按预期工作(更改背景和等)。但设置为false只能按预期工作一半 - 忽略单击,但不会将单击事件传递给父级。

因此,如果有人遇到同样的问题,请查看您的父母(或父母的父母)容器。如果它是可滚动的容器,您将面临更多挑战。

相关问题