【问题标题】:How to bring ImageView in front of Button in android 5?如何在 android 5 中将 ImageView 放在 Button 前面?
【发布时间】:2015-02-25 20:53:43
【问题描述】:

在 lolipop 之前的 android 版本中,以下代码有效,并且按钮前面有一个图像。但在 android 5 中,imageview 放在按钮后面。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/button"
    android:layout_width="210sp"
    android:layout_height="210sp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:background="@drawable/round_button"
    android:drawablePadding="10dip"
    android:gravity="center_vertical|center_horizontal" />


<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:contentDescription="@string/torch"
    android:src="?attr/imageview" />

 </RelativeLayout>

【问题讨论】:

  • 这些是否在RelativeLayout 中?
  • @CommonsWare 是的,他们在里面

标签: android android-5.0-lollipop


【解决方案1】:

问题出现在 Android 5.0 的 elevation 属性。显然,RelativeLayout Z 轴排序与elevation 绑定。如果两个小部件具有相同的elevationRelativeLayout 将确定 Z 轴顺序 - 例如,如果您将布局切换为两个 Button 小部件,您可以看到。但是,如果一个小部件 (Button) 具有 elevation,而另一个小部件 (ImageView) 没有,则 elevation 将优先。

您可以通过android:stateListAnimator="@null"defining your own custom animator 删除Button elevation。或者,您可以在ImageView 中添加一些elevation,使其在Z 轴上高于Button

【讨论】:

  • 澄清一下,一些小部件有一个预设的高度值,它会覆盖默认排序?
  • @LambergaR:我更倾向于将其表述为:一些小部件具有影响其高度的方面,例如默认为Button 设置的stateListAnimator
  • "android:stateListAnimator="@null" 这需要 API 级别 21 或更高,但我的 minsdkversion 是 19
  • 我终于可以在 Button 前面看到视图了
  • 最后,设置 android:stateListAnimator="@null" 是唯一适用于 28 9.0 的解决方案
【解决方案2】:

按钮高度和translationZ值在框架中定义如下:

<!-- Elevation when button is pressed -->
<dimen name="button_elevation_material">1dp</dimen>
<!-- Z translation to apply when button is pressed -->
<dimen name="button_pressed_z_material">2dp</dimen>

Source

就像 CommonsWare 解释的那样,将 ImageView 的 translationZ 设置为高于 Button 的值会得到预期的结果。

【讨论】:

    猜你喜欢
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多