ConstraintLayout 之 ConstraintSet 动态修改约束(动画)

1. 首先要声明一下ConstraintSet对象
private val set = ConstraintSet()
复制代码
2. 其次需要复制一份父布局的约束,方法有三个如下:
set.clone(constraintLayout: ConstraintLayout);
set.clone(set: ConstraintSet);
set.clone(context: Context, constraintLayoutId: Int);
复制代码

简单说明一下,如果要修改一个TextView的约束,需要找到TextView的父布局,然后调用上述方法clone一份

这里需要注意一下,在调用clone()方法的时候,必须保证这个父布局的所有子布局都设置了 id,不然会报如下错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.liuniukeji.lightlanguage/com.mufeng.light.ui.activity.CurriculumClassifyActivity}: java.lang.RuntimeException: All children of ConstraintLayout must have ids to use ConstraintSet
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: java.lang.RuntimeException: All children of ConstraintLayout must have ids to use ConstraintSet
        at android.support.constraint.ConstraintSet.clone(ConstraintSet.java:688)
复制代码
3. 第三步就需要去设置组件之间的约束了,常用方法有:
set.connect(startID: Int, startSide: Int, endID: Int, endSide: Int, margin: Int)

set.connect(startID: Int, startSide: Int, endID: Int, endSide: Int)
复制代码

例如: 修改一个id为text的TextView的约束,相依赖的约束组件为一个id为btn的Button,修改为text的左边和btn的左边对其,边距margin为20px:

set.connect(R.id.text,ConstraintSet.LEFT,ConstraintSet.R.id.btn,ConstraintSet.LEFT,20)
复制代码

设置text水平剧中于父布局parent

set.centerHorizontally(R.id.text, ConstraintSet.PARENT_ID)
复制代码

设置text的高度为10px

set.constrainHeight(R.id.text, 10);
复制代码
4.第四步 设置一个动画,并且要求api版本为19及以上
TransitionManager.beginDelayedTransition(rootLayout)
复制代码
5.最后一步 ,apply一下使设置生效
set.applyTo(rootLayout)
复制代码
ConstraintSet还提供了很多约束设置方法,详情请查看官方文档


你可能感兴趣的:(ConstraintLayout 之 ConstraintSet 动态修改约束(动画))