ConstraintLayout,子视图的高程和向后兼容性

时间:2018-10-15 10:51:50

标签: android android-layout android-constraintlayout

我有一个ConstraintLayout和一个Button和一个ImageView作为其子视图。将ImageView放在Button上方,期望将ImageView绘制到Button上方。 (当然,我可以使用Button将图像添加为可绘制对象。但是,在我的场景中,我想对按钮的宽度做一些动画处理,我希望ImageView保持原样)。但是,ImageView绘制在Button下方,因为Button在其默认状态[Material Design Guidline]上具有2dp仰角。按下按钮时,此高度升高到8dp。通常,我们需要将elevation的{​​{1}}或translationZ属性设置为大于2dp,以使ImageView出现在按钮上方。但是,在API级别21之前支持ImageView属性或elevation属性。我需要支持API级别19。而且,使用设计库尚无法实现高程。维持条件,是否有办法在translationZ内的ImageView上绘制Button

ConstraintLayout

3 个答案:

答案 0 :(得分:1)

您应该使用FrameLayout包裹按钮。它将使您可以在下面的视图之上堆叠视图。请参见以下示例:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />

    </FrameLayout>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>

答案 1 :(得分:0)

在xml中,剪切imageview的代码并将其粘贴到button的代码下方。旧设备不支持海拔高度

答案 2 :(得分:0)

这是我现在要使用的解决方案。根据android文档,稍后将绘制更高版本的兄弟。因此,通常,如果View作为布局文件中的同级元素稍后出现,它将在其他同级元素上绘制。但是,默认情况下该按钮具有高程,因此它将在Views上方绘制,而API中21以上的海拔高度较低。

我们可以在同级中设置elevationtranslationZ,使其显示在Button上方。我们还需要确保将要放在顶部的View放在布局的后面。在低于21的API中,海拔将不起作用,而后面的View将绘制在顶部。

相关问题