约束布局ConstraintLayout使用汇总

126 阅读3分钟

一、Android创建Avtivity默认布局

为什么使用约束布局

1.减少布局层级的嵌套 :LinearLayout左右上下嵌套,在布局解析时较慢

2.实现别得布局实现不了的:布局中实现特定角度的偏差

基本用法

1、控件之间基本关系(上下左右),而且还可以实现类似C#的控件拖动布局

坐标的基准点是手机的左上角,横为X,竖为Y,因为在二维坐标系中一个X一个Y就行确认唯一 位置,所以下面的在控件中至少有两个相对约束量,就能确认控件位置

例如:

左端和上端都是和父容器一起,那就是一个左上角的紧贴父容器的控件
app:layout_constraintStart_toStartOf="parent" 
app:layout_constraintTop_toTopOf="parent"
<!-- 我的什么位置在谁的什么位置 --> 
app:layout_constraintTop_toTopOf="" 我的顶部和谁的顶部对齐
app:layout_constraintBottom_toBottomOf="" 我的底部和谁的底部对齐 
app:layout_constraintLeft_toLeftOf=""我的左边和谁的左边对齐 
app:layout_constraintRight_toRightOf=""我的右边和谁的右边对齐 
app:layout_constraintStart_toStartOf="" 我的开始位置和谁的开始位置对齐 
app:layout_constraintEnd_toEndOf="" 我的结束位置和谁的结束位置对齐 
app:layout_constraintTop_toBottomOf="" 我的顶部位置在谁的底部位置 
app:layout_constraintStart_toEndOf="" 我的开始位置在谁的结束为止

2、基准线:

layout_constraintBaseline_toBaselineOf 
谁的基准线和谁的对齐

3、上下左右偏移

app:layout_constraintHorizontal_bias="" 水平偏移 取值范围是0-1的小
app:layout_constraintVertical_bias="" 垂直偏移 取值范围是0-1的小数

4、角度偏移:

app:layout_constraintCircle="" 目标控件id 
app:layout_constraintCircleAngle="" 对于目标的角度(0-360) 
app:layout_constraintCircleRadius="" 到目标中心的距离

5、控件布局Margin 和padding都是一样的,约束布局有一个Gone margin 字面意思就是消失时候的边距,也就是当被当做参照物的控件没了,目前控件的存在形式

<!-- GONE Margin --> 
app:layout_goneMarginBottom="0dp" 
app:layout_goneMarginEnd="0dp" 
app:layout_goneMarginLeft="0dp" 
app:layout_goneMarginRight="0dp" 
app:layout_goneMarginStart="0dp" app:layout_goneMarginTop="0dp"

进阶用法

1、约束布局中的weight weight在线性布局中很常见,用于按照比例或者剩余宽高度,来自动填充控件的宽高。约束布局中的weight是

app:layout_constraintWidth_default="spread|percent|wrap"    三选一
app:layout_constraintHeight_default="spread|percent|wrap"   三选一
  • 解释:spread就是默认,对比LinearLayout就是去除matgin&padding,填充满
  • 解释:percent 百分比,就是weightsum,控件进行设定就行
  • 解释:wrap字面已经是包裹包含的意思了,也就是在要求的宽高中,包裹里面文字,一般适配文件换行等

2、宽高比,一般UI给图都是按照比例决定,但是要求合weight一样,有一个不能给具体值,需要设置为0dp

android:layout_width="0dp" 
android:layout_height="100dp"
app:layout_constraintDimensionRatio="1:1"

==========================差不多够用了在基本布局=======================

over。。