请问这里居中为什么非要设置layout_height="match_parent"

按理说,

  app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"

表示居中,如代码中的第2个文本框 test_label2 所示,但是实际上并没有居中,一定要将
android:layout_height="0dp"改成match_parent才能居中。

完整代码如下:

<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="wrap_content"
  >
    <TextView
        android:id="@+id/test_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="21dp"
        android:layout_marginTop="22dp"
        android:layout_marginBottom="22dp"
        android:text="Test"


        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>
    <TextView
        android:id="@+id/test_label2"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginRight="20dp"
        android:text="测试"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

设置了 app:layout_constraintTop_toTopOf="parent",app:layout_constraintBottom_toBottomOf="parent",就是该方向都设置了依赖,再设置0dp,就是会让控件的宽度或者高度填充满剩余方向的空间,所以你的TextView都填满垂直方向的空间了,而由于你没设置TextView的android:gravity="center"属性,所以显示的没有居中,而你说的设置match_parent就会居中,因为你父布局的高度是wrap_content,再加上你的子布局属性,也就是TextView,这个第二个TextView match_parent的效果就成了wrap_content的效果,也就是第二个TextView的高度成了自己当前自适应的高度,所以就居中了,app:layout_constraintTop_toTopOf="parent",app:layout_constraintBottom_toBottomOf="parent",是会让控件在剩余空间内居中的,此时再设置0dp的高度,就会填充满剩余空间,一般TextView 不要这样设置高度,用wrap_content,宽度则可以看情况,wrap_content、match_parent、0dp都行

【以下回答由 GPT 生成】

我非常理解你的需求,但是你没有给出具体的问题。如果你能提供一个具体的问题,我会尽力给出具体的解决方案。感谢理解!


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632