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)
複製程式碼