应用 material 主题时按钮的渲染顺序错误

Wrong render order for button when material theme is applied

无论布局结构如何,按钮小部件都绘制在任何其他小部件之上。当应用 Material Dark/Light 主题时,它会在 RelativeLayout 和 FrameLayout 中重复。请查看下面的屏幕截图,以更好地说明这种奇怪的行为。

在 Nexus 4 和 Nexus 5 上检查过。但是我怀疑它与设备有关。

Android 5.0 Lollipop 和 Material Design 引入了新的 属性 来指定小部件的高度(Z 索引)。它被描述为 here.

要在按钮上绘制视图,您可以将 android:elevation="1dp" 添加到视图

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Don't look so deep"
    />
<View
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C00"
    android:elevation="1dp"
    />

以下是之前对被误解问题的回答的一部分,保留以备将来参考

使用 RelativeLayout,您必须指定元素相对于其他元素的位置。

所以说你想在按钮下方设置 View,你必须将 id 添加到元素并指定视图在按钮下方:

<Button
    android:id="+id/myactivity_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Don't look so deep"
    />
<View
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C00"
    android:layout_below="@id/myactivity_button"
    />

查看 Android Developer Guide for RelativeLayout and the available LayoutParameters for RelativeLayouts


FrameLayout 通常不利于组织多个组件。 FrameLayout 旨在遮挡屏幕上的一个区域以显示单个项目。可以使用 android:layout_gravity 属性控制 FrameLayout 子项的位置。

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:text="Don't look so deep"
    />
<View
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C00"
    android:layout_gravity="bottom"
    />

查看 Android docs for FrameLayout and the available parameters for the layout_gravity

从 Lollipop (API 21) 开始,Android 默认将 高度/Z 动画 应用于按钮。为避免这种情况,请将以下内容添加到您的 Button XML:

<Button
    ...
    android:stateListAnimator="@null"
/>

这将使按钮遵循其 Z 索引。

Source