android - ConstraintLayout 使 View 高度 x sibling 的百分比

标签 android android-constraintlayout android-percentrelativelayout

我想知道是否可以使用 Constraintlayout 实现以下目标:

enter image description here

我有一个固定比例 (2:1) 的图像,并希望它用渐变叠加,渐变应该从图像的底部开始,然后将其顶部对齐到图像高度的 50%。 据我所知,这是不可能的。 使用 Guideline 不起作用,因为它只能放置在 Percentage to the Parent/Layout 使用 weight 只能在 Chains 中使用,但是因为我需要覆盖两个 View 链,所以不能使用,对吗?

最佳答案

你可以像下面这样实现:

<?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">


    <ImageView
        android:id="@+id/imageView4"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintDimensionRatio="2:1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/darker_gray" />

    <View
        android:id="@+id/View_Top"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintDimensionRatio="4:1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/transparent" />

    <View
        android:id="@+id/View_Bottom"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintDimensionRatio="4:1"
        app:layout_constraintTop_toBottomOf="@id/View_Top"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/holo_orange_dark" />



    </android.support.constraint.ConstraintLayout>

此处 imageView 设置为 2:1 比例,并在上面的 Imageview 中设置了 2 个额外 View ,其中 View_Top 是透明的,View_Bottom 是 imageview 的下半部分,因此您可以在 View_Bottom 中设置渐变。

下图中背景颜色为灰色,您的颜色可以替换为 View_Bottom 颜色

enter image description here 希望它能帮到你..!

关于android - ConstraintLayout 使 View 高度 x sibling 的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49514205/

相关文章:

android - 即使与父级匹配,ConstraintLayout 列表项的长度也不相同?

android - 如何在 PercentRelativeLayout 中使百分比动态化?

android - 如何在 CollapsingToolbarLayout 中使用 PercentRelativeLayout?

Android - 将按钮放在 ImageView 上的确切位置

java - 滚动时图像滞后如何解决?

java - 如何将复杂的 hashmap 转换为 arrayList

android - ConstraintLayout 匹配兄弟 View 高度,以较高者为准

android - 实现 firebase-analytics 和 play-service-analytics 后 Google Play 中出现广告警告

Android Studio 0.2.5 不将 Galaxy S4 视为设备

android - 使用 Flow 时 MissingConstraints lint 错误