如何从ConstraintSet中获取指定方向已连接视图以在指定View前插入新View
实现方案
你可以用ConstraintSet提供的getConnection()方法获取指定View对应方向的约束信息,无需额外传入insertAfter参数,修改后的代码如下:
private void insertBefore(int toInsert, int insertBefore) { ConstraintSet cs = new ConstraintSet(); ConstraintLayout root = findViewById(R.id.constraintRoot); cs.clone(root); // 获取insertBefore原本的顶部约束信息 ConstraintSet.Connection topConnection = cs.getConnection(insertBefore, ConstraintSet.TOP); int oldTargetId = topConnection.target; int oldTargetSide = topConnection.targetSide; int oldMargin = topConnection.margin; // 先断开insertBefore原来的顶部约束 cs.clear(insertBefore, ConstraintSet.TOP); // 把insertBefore的顶部连到待插入View的底部 cs.connect(insertBefore, ConstraintSet.TOP, toInsert, ConstraintSet.BOTTOM, 0); // 待插入View的顶部连到原来insertBefore的顶部目标,沿用原来的margin cs.connect(toInsert, ConstraintSet.TOP, oldTargetId, oldTargetSide, oldMargin); // 保持两个View的左右约束一致,避免横向错位 ConstraintSet.Connection leftConnection = cs.getConnection(insertBefore, ConstraintSet.LEFT); cs.connect(toInsert, ConstraintSet.LEFT, leftConnection.target, leftConnection.targetSide, leftConnection.margin); ConstraintSet.Connection rightConnection = cs.getConnection(insertBefore, ConstraintSet.RIGHT); cs.connect(toInsert, ConstraintSet.RIGHT, rightConnection.target, rightConnection.targetSide, rightConnection.margin); root.setConstraintSet(cs); }
注意事项
- 如果原来的
insertBefore是垂直链的一部分,需要额外调用cs.createVerticalChain()更新链结构,避免链失效 - 如果你的布局使用的是
start/end而非left/right做横向约束,把对应代码里的LEFT/RIGHT替换成START/END即可 - 待插入的View需要提前添加到
ConstraintLayout中,再调用此方法修改约束才会生效
内容的提问来源于stack exchange,提问作者Samuel
相关产品推荐
相关产品推荐

