在 ConstraintLayout 中以编程方式添加视图

Add a view programmatically in ConstraintLayout

我尝试在 ConstraintLayout 中的另一个 View 的相同位置添加一个 View,但是添加的 View 没有获得另一个 View 的 LayoutParams。

添加的视图位于容器的顶部|左侧。

这是我的代码:

TextView cloneView = new TextView(getContext());
cloneView.setLayoutParams(otherView.getLayoutParams());
mainContainer.addView(cloneView);

要向 ConstraintLayout 添加视图,您必须使用 ConstraintSet 添加约束。

View v = findViewById(...);
ConstraintLayout cl = (ConstraintLayout) findViewById(...);


ConstraintSet c = new ConstraintSet();
cl.addView(v);
int id = v.getId();

c.clone(cl);
c.connect(id, ConstraintSet.Top, otherViewIdAboveV, ConstraintSet.BOTTOM, 0);
...
other constraints
...
c.applyTo(cl);