【问题标题】:Wrong render order for button when material theme is applied应用材质主题时按钮的渲染顺序错误
【发布时间】:2023-03-03 11:03:02
【问题描述】:

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

在 Nexus 4 和 Nexus 5 上进行了检查。但我怀疑它与设备有关。

【问题讨论】:

  • 我还注意到在某些情况下绘制顺序不是从上到下。

标签: android android-layout android-theme


【解决方案1】:

Android 5.0 Lollipop 与 Material Design 一起引入了新属性来指定小部件的高度(Z-index)。它被描述为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 RelativeLayoutavailable LayoutParameters for RelativeLayouts


FrameLayout 通常不适合组织多个组件。 FrameLayout 旨在阻止屏幕上的一个区域以显示单个项目。 FrameLayout子元素的位置可以通过android:layout_gravity属性来控制。

<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 FrameLayoutavailable parameters for the layout_gravity

【讨论】:

  • @holtaf :你可以从他的例子中看到他使用的是相对布局。如果他没有指定小部件的布局选项,它们将全部绘制在彼此之上。因此,问题的解决方案(据我所知)是将布局选项添加到他的布局 xml。
  • 是的,它们会在彼此之上绘制,这不是问题,问题是它们的绘制顺序。他们假设按顺序绘制,从上到下,但他们从下到上绘制..
  • @holtaf ,你是对的。虽然我无法重现我身边的问题。视图完全绘制在 Button 上。
  • @arnfada 你试过用材料主题重现它吗?仅当设置了材质主题时才会发生。你能告诉我你使用的是什么版本的支持库吗?
  • @arnfada 你是对的人,改变海拔解决了这个问题,但我认为我有更好的解决方案。要完全删除按钮高度,请执行以下操作:&lt;Button ... android:stateListAnimator="@null" /&gt; 这将删除控制按钮高度的stateListAnimator
【解决方案2】:

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

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

这将使按钮尊重其 Z-index。

Source

【讨论】:

  • 感谢您的回答,您节省了我的时间。它也在 MaterialButton 上工作。
猜你喜欢
  • 2019-11-02
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 2016-10-17
相关资源
最近更新 更多