首页 > 解决方案 > 约束布局中的 dp 和 wrap_content

问题描述

使用约束布局时 0 dp 和 wrap_content 有什么区别?是效率问题吗?我已经尝试过同时使用它们,但我只是不明白有什么区别。

标签: javaandroidkotlin

解决方案


实际上,0dp它完全占据width/height了它的受限区域,而wrap_content占据了它所需要的任何东西来保持它的内容。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    android:padding="16dp">


    <Button
        android:id="@+id/button_wrap"
        android:text="Wrap Button"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


    <Button
        android:id="@+id/button_0dp"
        android:text="0dp Button"
        app:layout_constraintTop_toBottomOf="@+id/button_wrap"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_width="0dp"
        android:layout_height="wrap_content"/>

</androidx.constraintlayout.widget.ConstraintLayout>

输出:

在此处输入图像描述

在上面的例子中

  • Buttonwith只占用保存Wrap Buttonwrap_content所需的空间,而
  • Buttonwith0dp占用其受限区域中的所有空间

推荐阅读