android - ConstraintLayout - 与自身成比例的宽度/高度?

标签 android android-constraintlayout

我正在尝试弄清楚如何使用约束布局实现以下行为:

  1. 在 ConstraintLayout 父级的中心放置一个 View
  2. 使 View 宽度为父 View 宽度的一半
  3. 使 View 的高度等于它的宽度

(即 - 在中心放置一个正方形)

我尝试使用这个组合:

  android:layout_width="0dp"
  android:layout_height="0dp"
  app:layout_constraintBottom_toBottomOf="parent"
  app:layout_constraintEnd_toEndOf="parent"
  app:layout_constraintStart_toStartOf="parent"
  app:layout_constraintTop_toTopOf="parent"
  app:layout_constraintDimensionRatio="2:1"

但我不确定如何从这里继续

最佳答案

您无需指南即可轻松完成。

只需使用app:layout_constraintWidth_percent="0.5"

它适用于 ConstraintLayout:1.1.0-beta5 及更高版本。

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/img_icon"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@color/dark_red"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent="0.5" />

</android.support.constraint.ConstraintLayout>

enter image description here

关于android - ConstraintLayout - 与自身成比例的宽度/高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49639231/

相关文章:

android - ConstraintLayout ListView RTL 有些行不是RTL

android - 数据绑定(bind)布局约束

android - 在自定义 ViewGroup 中设置单个 onClick 事件

Android Adb 错误

Android 在触摸 ListView 时删除软键盘

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

android - 无法加载 AppCompat ActionBar 约束布局 Android Studio 3.1.3

Android ViewPager 无法加载第三个 fragment

安卓 WebView : Remove pop-out option in google drive/doc viewer

android - 约束布局在应用程序运行时不显示来自 ImageView 的图像