如何将view1的垂直中心设置为view2的垂直中心?
val view1 = ConstraintLayout(context)
view1.layoutParams = ConstraintLayout.LayoutParams(100, 200)
view1.id = View.generateId()
val view2 = ConstraintLayout(context)
view2.layoutParams = ConstraintLayout.LayoutParams(50, 100)
view2.id = View.generateId()
layout.addView(view1)
lyout.addView(view2)
val cs = ConstraintSet()
cs.clone(layout)
//setting position of view1
cs.connect(view1.id, ConstraintSet.TOP, layout.paddingTop, ConstraintSet.TOP, 50)
cs.connect(view1.id, ConstraintSet.START, layout.paddingStart, ConstraintSet.START, 100)
//setting postion of view2
cs.connect() // ??? no option like "ConstraintSet.VERTICAL_CENTER"
cs.connect(view1.id, ConstraintSet.paddingEnd, view2.paddingStart, ConstraintSet.START, 100)
cs.applyTo(layout)
我应该在ConstraintSet中编写什么来实现这样的布局:
|------|
| | |---|
| | - - | |
| | |---|
|------|
答案 0 :(得分:0)
通常,您可以同时应用顶部和底部约束(垂直居中)或开始+结束约束(水平居中)或两者都居中。
如果您希望view2
相对于view1
垂直居中,则可以通过两次connect()
调用来做到这一点:
cs.connect(view2.getId(), ConstraintSet.TOP, view1.getId(), ConstraintSet.TOP);
cs.connect(view2.getId(), ConstraintSet.BOTTOM, view1.getId(), ConstraintSet.BOTTOM);
当然,您还可以使用一种便捷的方法:
cs.centerVertically(view2.getId(), view1.getId());