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

Ben*_*ihr 8 android android-constraintlayout

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

添加的视图发生在容器的左上角|。

这是我的代码:

TextView cloneView = new TextView(getContext());
cloneView.setLayoutParams(otherView.getLayoutParams());
mainContainer.addView(cloneView);
Run Code Online (Sandbox Code Playgroud)

Jua*_*uan 10

要将视图添加到 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);
Run Code Online (Sandbox Code Playgroud)