onunix 2023-08-28 18:54 采纳率: 80%
浏览 6
已结题

请问这里居中为什么非要设置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>

  • 写回答

3条回答 默认 最新

  • 饼子会飞 2023-08-29 08:22
    关注

    设置了 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都行

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 9月6日
  • 已采纳回答 8月29日
  • 修改了问题 8月28日
  • 修改了问题 8月28日
  • 展开全部

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?