以相对布局为例
- 创建约束
// 设置约束
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.width = childrenSize;
layoutParams.height = childrenSize;
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
- 添加约束
childrenView.setLayoutParams(layoutParams);
- 添加相对约束的时候注意:
// 代码创建的view是getId默认的-1,需要调用setId 才会使得约束成立
beforeView.setId(111000+i);
layoutParams.addRule(RelativeLayout.BELOW,beforeView.getId());