Android - 在RelativeLayout中,5.0及以上版本中Button覆盖TextView的问题

3
我需要实现的目标: 在一个按钮上方,有两行文本和一条直线,始终显示。因此,在这种情况下,按照我的了解,不能在Button的属性中设置文本。因此,我使用TextViewView对齐到Button的顶部来实现它。 问题: 我遇到了Android 5.0+的奇怪UI外观问题,即当启用Button时,它会覆盖TextViewView,即使在RelativeLayoutxml文件中TextViewButton之前。(根据我的理解,这意味着TextView应该在Button的顶部)以下是我的xml代码:
<RelativeLayout
    android:id="@+id/rl_daily_check_in_button_container"
    android:layout_width="140dp"
    android:layout_height="140dp"
    android:layout_marginBottom="4dp"
    android:layout_centerHorizontal="true"
    android:layout_above="@+id/textview_check_in_days_in_row">

    <Button
        android:id="@+id/button_daily_check_in"
        android:layout_width="140dp"
        android:layout_height="140dp"
        android:background="@drawable/daily_checkin_button" />

    <TextView
        android:id="@+id/textview_check_in"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_above="@+id/view_line"
        android:layout_marginBottom="4dp"
        android:text="@string/title_not_yet_daily_check_in"
        android:textColor="@color/text_gray"
        android:textStyle="bold"
        android:textSize="36sp" />

    <View
        android:id="@+id/view_line"
        android:layout_width="94dp"
        android:layout_height="1dp"
        android:layout_centerHorizontal="true"
        android:layout_above="@+id/textview_check_in_points"
        android:layout_marginBottom="6dp"
        android:background="@color/text_gray" />

    <TextView
        android:id="@+id/textview_check_in_points"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="@string/points_can_get_daily_check_in_placeholder"
        android:textColor="@color/text_gray"
        android:textSize="14sp" />
</RelativeLayout>

但是当应用程序在Android 5.0-(例如4.4.2)中时,UI正好符合我的期望。我尝试设置android:elevation="xxdp"属性,直到我以编程方式设置了Button的背景才成功。有人可以解释一下原因以及Andoird 5.0+如何呈现其UI吗?非常感谢!

Andoird 5.0+上的Button

enter image description here

Button 在 Android 5.0- 上:

enter image description here


1
通过将“Button”替换为“ImageView”解决了问题...不知道为什么这种方法有效。有人能讲述更多的故事吗? - Desmond DAI
1个回答

5
从Android Lollipop(5.0)开始,Button具有默认的StateListAnimator。它将默认的android:elevationandroid:translationZ属性设置为Button。由于Button具有默认高度,因此它会显示在没有高度设置(比较确切的是高度小于Button的视图)的其他视图上方。即具有较高高度设置的视图将显示在具有较低高度设置的视图上方。
因此,当您将Button更改为ImageView时,问题得到解决,因为ImageView没有默认的elevation设置。

我有过相反的经历。我没有注意到我的主视图重叠了我的AppBar,因为在5.0+上AppBar被提高了。当我在pre5.0上测试时,AppBar无法被看到。我的解决方案只是为主视图添加一个顶部边距。 - Fletcher Johns
你可以将应用栏和主视图放在一个垂直的LinearLayout中。 - Bob
@Dinesh Bob,感谢您的回答。您是从哪里获取这些信息的?是来自官方文档还是Android提供的说明? - Yuliia Ashomok
我以前在某个地方读过这种方法,当时是在Lollipop版本中。按钮具有默认的高程设置。从Lollipop开始,具有更高高程的视图将被绘制在其他视图上方。实际上,我们的应用程序也遇到了类似的问题。 - Bob

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