ConstraintLayout(约束布局)之初学

一、作用

解决多层嵌套布局影响性能的问题。

二、用法

1.相对定位

如上图布局,在约束布局中,其中中间Home的id为message,垂直和水平方向都是居中,布局如下:

<TextView
    android:id="@+id/message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/title_home"
    android:background="@color/colorPrimary"
    android:textColor="#fff"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"/>

重点就在最后四条,按照字面意思理解四句话分别是:

message的左边约束到父级的左边;

message的上边约束到父级的上边;

message的右边约束到父级的右边;

message的下边约束到父级的下边。

这里的“约束到”,有点对齐的意思。同时具有这四个属性才能使其在屏幕中心位置。

其余四个TextView分别为tv1, tv2, tv3, tv4,挑几个简单的记录:

① text1的实现:参照相对布局的方式,应该是使用类似于toRightOf的属性。但是写上以后发现TextView报红提示:

This view is not constrained vertically: at runtime it will jump to the top unless you add a vertical constraint.

大概意思是说这个view没有在垂直方向上没有被约束,如果不加上垂直方向上的约束在运行时这个view会跳到顶部。

那么参照message的写法,加上

<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toRightOf="@id/message"
    android:text="我是text1"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"/>

即把tv1的左边约束到message的右边,同时实现垂直方向上的居中,这样就实现了和message保持同一水平线。

也有另一种写法也能实现相同效果:

<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toRightOf="@id/message"
    android:text="我是text1"
    app:layout_constraintBaseline_toBaselineOf="@id/message"/>

这里的Baseline指的是文本基线,toBaselineOf可以使两个控件文本垂直方向上对齐,相当于对齐两者的下划线。

②tv2的实现:同样地通过约束相对位置来实现:

<TextView
    android:id="@+id/tv2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="我是text2"
    app:layout_constraintTop_toBottomOf="@+id/message"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>

还是要注意,必须同时在水平和垂直方向上对控件进行约束。

其他两个实现方式相同,就不再赘述。

2.角度定位

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值