无法使一个视图覆盖FrameLayout中的另一个视图

6
我想把我的ImageView放在Button的上方,但是无论我选择哪种布局或排列方式,按钮始终会覆盖ImageView...这是我尝试过的一个FrameLayout的示例代码:

编辑: 为简化我的问题:为什么FrameLayout不能正常工作?(你可以把这段代码复制到你的Android Studio中看一下)

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:padding="0.1dp">

    <Button
        android:clickable="false"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:text="135"
        android:background="@android:color/holo_blue_bright"
        android:layout_gravity="center"
        android:id="@+id/buttonText"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/triangle"
        android:id="@+id/triangle"
        android:paddingTop="5dp"
        android:layout_gravity="center_horizontal|bottom" />

</FrameLayout>
4个回答

6

我遇到了同样的问题(需要注意的是,如果按钮被禁用,它不会覆盖所有其他视图),并找到了解决方法。只需将按钮和图像分别包装在单独的子框架布局中即可。

<FrameLayout>...
    <FrameLayout>...
        <Button ... />
    </FrameLayout>
    <FrameLayout>...
        <ImageView ... />
    </FrameLayout>
</FrameLayout>

我不确定这是否会有任何负面影响,除了可能有一点效率低下,但它似乎正常工作。


1
你的解决方案对我很有用;但是,没有必要将两个视图都包装在FrameLayout中,或者根本不需要将它们都放在FrameLayout中,只需将我想要放在后台的那个视图包装起来即可。编辑:澄清 - Nikaoto

5
在 Android 5.0 (API 21) 及以上版本中,你必须将 android:elevation 添加到视图中。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:padding="0.1dp">

    <Button
        android:clickable="false"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:text="135"
        android:background="@android:color/holo_blue_bright"
        android:layout_gravity="center"
        android:id="@+id/buttonText"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/triangle"
        android:id="@+id/triangle"
        android:paddingTop="5dp"
        android:layout_gravity="center_horizontal|bottom"
        android:elevation="3dp" />

</FrameLayout>

0
您可以在想要置于前方的视图上调用bringToFront()。
示例:
yourView.bringToFront();

bringToFront() 对我不起作用...也许我在使用 FrameLayout 时做错了什么? - james
你为什么要使用帧布局呢?难道不能用相对布局来实现吗? - Aawaz Gyawali
我尝试使用RelativeLayout,但没有成功,所以我尝试了FrameLayout,因为覆盖视图是FrameLayout的主要用途。 - james
使用RelativeLayout,在Java代码中使用view.bringToFront();。我敢打赌它会起作用。 - Aawaz Gyawali
请编辑您的问题,添加分配视图并使用bringToFront()的代码片段。我认为您在Java代码中做错了什么。 - Aawaz Gyawali
显示剩余2条评论

-1

我通过将Button更改为TextView来自己解决了这个问题。在这里,FrameLayout的默认行为不起作用,因为Android系统总是将按钮设置为覆盖其他视图(这样用户就始终能够单击该按钮)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接