自從用了ConstraintLayout,發(fā)現(xiàn)布局寫法又升華了,嵌套減少了,層次更清晰了。
在ConstraintLayout出來之前,就是在LinearLayout、RelativeLayout時代,如果想要在代碼中動態(tài)修改布局中控件的尺寸、位置、與其他控件的相對關(guān)系等,我們都用的是LayoutParams,在剛接觸ConstraintLayout的時候,我也以為仍然是用LayoutParams,結(jié)果發(fā)現(xiàn)有ConstraintSet這么一個好東西,簡直事半功倍~
1,首先,要聲明一下ConstraintSet對象。
ConstraintSet set =new ConstraintSet();
2,其次,會有三個clone方法,可以任選其一。
set.clone(ConstraintLayout constraintLayout);
set.clone(ConstraintSet set);
set.clone(Context context, int constraintLayoutId);
clone方法你可以這么理解:
比如你的父布局是ConstraintLayout,名為rootLayout,rootLayout下有若干控件,而你只需動態(tài)修改一個TextView的相對位置或者尺寸,那么你就要先set.clone(rootLayout);等于copy了整個布局的控件與屬性,然后做下面的事情。。。
3,挑幾個有代表性的屬性說一下:
①
set.connect(int startID, int startSide, int endID, int endSide, int margin);
設置mViewSwitcher控件的頂邊與mTitleView的底邊對齊,且之間margin值是50px:
set.connect(mViewSwitcher.getId(), ConstraintSet.TOP, mTitleView.getId(), ConstraintSet.BOTTOM, 50);
②
set.centerHorizontally(int viewId, int toView)
設置mTimeView水平劇中于parent
set.centerHorizontally(mTimerView.getId(), ConstraintSet.PARENT_ID);
③
set.constrainHeight(int viewId, int height);
設置mStateLine的高度為2px
set.constrainHeight(mStateLine.getId(), 2);
4,最后,apply一下使設置生效
set.applyTo(rootLayout);
最后說一下:
ConstraintSet還提供了上述第三步方法中的重載方法以及其他沒提到的一些方法,比如:
setGuidelinePercent()
removeFromVerticalChain()
setVerticalChainStyle()
setTranslation()
setScaleX()
等等,基本滿足了可以在xml中設置的那些屬性。
OK,用起來吧童鞋們~~
