约束布局中的dp和wrap_content

时间:2020-01-05 20:20:12

标签: java android kotlin

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

3 个答案:

答案 0 :(得分:2)

实际上,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>

输出:

enter image description here

在上面的示例中

  • Buttonwrap_content仅占用按住 Wrap Button 所需的空间,而
  • Button0dp一起占用了受限区域中的所有空间

答案 1 :(得分:0)

主要区别在于 wrap_content 仅考虑其大小,并且不会使用附加的约束。

对于 0dp ,将使用约束。

答案 2 :(得分:0)

换行内容主要占据所需的确切空间,0dp宽度表示在宽度侧小于0dp大小。更好地理解只是改变宽度大小,我的意思是0到上限值