ConstraintLayout最大宽度百分比

Hyh*_*age 8 android android-layout android-studio android-constraintlayout

我一直在试验ConstraintLayout,有没有办法将视图的最大宽度设置为父级的百分比(以及匹配约束的高度和1:1的尺寸比)?

这是不使用最大宽度的代码:

<?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"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">

   <FrameLayout
      android:id="@+id/frameLayout3"
      android:layout_width="0dp"
      android:layout_height="259dp"
      android:layout_marginEnd="8dp"
      android:layout_marginStart="8dp"
      android:background="@android:color/black"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintHorizontal_bias="0.0"
      app:layout_constraintStart_toEndOf="@+id/imageView"
      app:layout_constraintTop_toTopOf="parent"/>

   <ImageView
      android:id="@+id/imageView"
      android:layout_width="0dp"
      android:layout_height="0dp"
      android:src="@android:drawable/ic_menu_add"
      app:layout_constraintBottom_toBottomOf="@+id/frameLayout3"
      app:layout_constraintDimensionRatio="1:1"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintWidth_percent="0.3"/>

</android.support.constraint.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)

这是结果:

片剂

电话

小智 38

我使用两个属性实现了最大宽度百分比:

app:layout_constraintWidth_max="wrap"
app:layout_constraintWidth_percent="0.4" 
Run Code Online (Sandbox Code Playgroud)

例:

<TextView
    android:id="@+id/textView2"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:text="Helo world"
    android:textAlignment="viewStart"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintWidth_max="wrap"
    app:layout_constraintWidth_percent="0.4" />
Run Code Online (Sandbox Code Playgroud)

并且文本宽度将最大增加到父项的4%,如果更多,它将包装内容.

  • 这是一个很好的提示。那行得通,应该是公认的答案。 (4认同)