在ConstraintLayout中以编程方式添加视图 [英] Add a view programmatically in ConstraintLayout
本文介绍了在ConstraintLayout中以编程方式添加视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试在ConstraintLayout中将另一个View添加到另一个View的同一位置,但是添加的View无法获得另一个View的LayoutParams.
I try to add a View at the same place of an other View in a ConstraintLayout but the added View don't get the LayoutParams of the other View.
添加的视图位于容器的顶部|左侧.
The added View take place on the top|left of the container.
这是我的代码:
TextView cloneView = new TextView(getContext());
cloneView.setLayoutParams(otherView.getLayoutParams());
mainContainer.addView(cloneView);
推荐答案
要将视图添加到ConstraintLayout中,必须使用ConstraintSet添加约束.
To add views to a ConstraintLayout you have to add the constraints using a 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);
这篇关于在ConstraintLayout中以编程方式添加视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文