android ConstraintLayout布局 详解

本文详细介绍了Android的ContraintLayout,它允许开发者通过约束定义控件的位置,提供更灵活的布局管理。相比于RelativeLayout和LinearLayout,ContraintLayout在减少布局层级、提高性能方面具有优势。讲解了如何设置控件居中、bias偏移,以及控件的尺寸约束,包括固定尺寸、wrap_content和match_constraint。此外,还提到了使用layout_constraintDimensionRatio属性实现控件的宽高比约束,以实现比例布局。通过对ContraintLayout的深入理解,可以提升Android应用的界面设计和性能表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ContraintLayout布局的约束性:
约束布局,控件之间,控件与父布局之间具有约束关系,控件的位置是按照约束来计算的;子view通过一个个约束的属性,来决定自己的位置;
RelativeLayout可以实现对控件的约束,实现起来相对简单;而LinearLayout虽然使用简单,但是会加深布局深度层级,影响app的解析效率问题;
ContraintLayout的其他属性和relativelayout基本一致,同时ContraintLayout可以约束控件的比例(LinearLayout中的weight属性)
设置居中和bias:
居中的方式可以使用左边和右边两个方向同时约束来定位布局的位置:
<android.support.constraint.ConstraintLayout ...>
  <Button android:id="@+id/button" ...
          app:layout_constraintLeft_toLeftOf="parent"
          app:layout_constraintRight_toRightOf="parent/>
</>
bias:
可以使用bias进行控件的偏移设置:
<android.support.constraint.ConstraintLayout ...>
  <Button android:id="@+id/button" ...
          app:layout_constraintHorizontal_bias="0.3"
          app:layout_constraintLeft_toLeftOf="parent"
          app:layout_constraintRight_toRightOf="parent/>
</>
控件尺寸约束:在ConstraintLayout中设置控件的宽度和高度是通过Android:layout_width和Android:layout_height来指定,但是有三种不同类型:
1.使用确定的尺寸,给定数值,比如36dp
2.使用wrap_content,该效果与其他控件相同
3.使用0dp来表示match_constraint,意思是根据约束规则制定宽度和高度(根match_parent效果是相同的)
设置控件的宽高比:
Layout_constraintDimensionRatio限制宽高比,如果使用宽高比来约束尺寸,则至少要设置宽高其中的一个尺寸为0dp,然后在设置上layout_contraintDimensionRatio属性;
<Button android:layout_width="wrap_content"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1" />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值