2018年2月8日,Google发布了ConstraintLayout 1.1.0 beta5版本(可以去googleblog查看更新日志),尽管还处于一个试用的版本,但是增加了几个很有用的功能。对于之前无法使用ConstraintLayout做到的功能,现在都是可以做到了。先介绍几个试用场景。

要实现VIP这个右下角的图标超过原有头像边界,如果使用FrameLayout
很好做,定义FrameLayout
的宽超出头像宽几个dp,高超出头像高几个dp,让vip图标居右下,让头像居左上,就可以实现这个效果。
可是使用ConstraintLayout
的话,没法做,如果你让VIP图标的底部和头像底部建立约束条件,那么VIP图标就紧紧和头像底部边界结合在一起,就没法通过margin或者其他方式实现下偏移。那么使用ConstraintLayout如果实现上述那种效果呢?
答案是借助两条参考线GuideLine
,建立右边的参考线,定义其距离偏移开始位置的距离,建立下方的参考线,定义其距离偏移开始位置的距离,然后让VIP图标依赖右边和下方的参考线,从而实现该效果。可以看到还是很麻烦的。



接下来我们借助1.1.0 beta 5增加的功能来实现这个效果.
使用版本1.1.0 beta 5来完成
- 添加依赖
dependencies {
compile 'com.android.support.constraint:constraint-layout:1.1.0-beta5'
}
- 功能 Circular positioning 介绍
使用角度和半径来约束一个控件的中心和另外一个空间的中心- 三个属性使用:
layout_constraintCircle : 本控件需要和哪个控件建立约束,这里填写那个控件的id,这里就是头像的id
layout_constraintCircleRadius : 本控件距离那个控件中心的半径距离
layout_constraintCircleAngle : 本控件距离那个控件中心的角度偏移,0-360°
- 三个属性使用:


- 实验效果:

我们可以看到,去掉了右方和下方的辅助线,简单就实现了刚才的功能,我们来看看加了多少代码.
<!--头像-->
<ImageView
android:id="@+id/head"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginStart="14dp"
android:contentDescription="@null"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="@id/guide_line_my_top"
tools:src="@drawable/default_contact_large_round_head_icon"/>
<!--VIP标识-->
<ImageView
<!--这是增加的代码-->
app:layout_constraintCircle="@id/head" 建立和头像控件的约束,如果此时不定义半径和角度,那么VIP标识在控件中心
app:layout_constraintCircleRadius="27dp" 如果只设置半径没有设置角度偏移的话,此时VIP标识在中间上方
app:layout_constraintCircleAngle="135" 此时实现了想要的效果
android:contentDescription="@null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/vip"/>



网友评论