2017-03-16 95 views
0

我尝试在ConstraintLayout中的其他View的相同位置添加View,但添加的View没有获得其他View的LayoutParams。在ConstraintLayout中以编程方式添加视图

添加的视图发生在容器的顶部。

这是我的代码:

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

回答

1

添加视图一个ConstraintLayout你必须添加使用约束集的约束。

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); 
+0

clone() - 从布局中复制约束条件,如果布局是父对象且没有约束条件,该怎么办? –

+0

@PavelPoley我不知道我是否理解评论。这种情况是,父母是一个ConstraintLayout,通过这样做,你可以通过相应的约束将Views添加到它。如果在添加新视图时没有约束条件,仍然需要为其添加新的约束条件。 – Juan

相关问题