首页 > 解决方案 > ConstraintLayout中,没有`weight`属性的情况下,android:layout_width="0dp"是什么意思?

问题描述

我有这个布局:

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlayGoogleMaterialIcons">

  <LinearLayout
      android:layout_height="wrap_content"
      android:layout_width="0dp">

...

android:layout_width="0dp"not in child of 是什么意思LinearLayout

android:layout_width="0dp"没有weight属性时是什么意思?

标签: androidandroid-constraintlayoutandroid-layout-weight

解决方案


对于ConstraintLayout如果你设置了约束的孩子,那么0dp就是 for match_constraint(take full width, or full height)

使用 0dp,相当于“MATCH_CONSTRAINT” https://developer.android.com/reference/android/support/constraint/ConstraintLayout

例子

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

    <TextView
        android:id="@+id/tv_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:text="text1" />

    <TextView
        android:id="@+id/tv_2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toStartOf="@id/tv_3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_1"
        tools:text="text2" />

    <TextView
        android:id="@+id/tv_3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/tv_2"
        app:layout_constraintTop_toBottomOf="@id/tv_1"
        tools:text="text3" />
</android.support.constraint.ConstraintLayout>

在此处输入图像描述

在上面的代码(和图像)中,您看到text1 TextView宽度是编写文本所需的宽度text1

对于 text2 和 text3TextView它需要整个宽度除以 2 这就是约束所说的


推荐阅读