FrameLayout中底层组件还能接收到touch事件解决办法

2016-10-12  本文已影响1401人  2ece9f02c806

最近在项目开发中遇到个问题,看下面这个layout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/frame1"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Button"/>
    </FrameLayout>


    <FrameLayout
        android:id="@+id/frame2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff">

    </FrameLayout>
</FrameLayout>

frame1在最底层,里面有一个占全屏那么大的Button,给Button一个OnClickListener,点击时弹一个toast。
frame2在最项层,里面没任何东西,把背景设为白色,这样就看不到frame1里的Button了。
现在在frame2是点击一下,发现会弹出toast!说明点击事件越过frame2传到frame1去了~

想要点击事件不传到frame1,可以把frame2的clickable属性设为true

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/frame1"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Button"/>
    </FrameLayout>


    <FrameLayout
        android:id="@+id/frame2"
        android:clickable="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff">

    </FrameLayout>
</FrameLayout>

这样一来touch事件就被frame2“吃掉了”不会传到frame1了

上一篇下一篇

猜你喜欢

热点阅读