如何以编程方式将视图和约束添加到ConstraintLayout?

问题描述 投票:31回答:1

我有一个问题,以编程方式将视图添加到Constraint Layout,并设置布局工作所需的所有约束。

我现在拥有的东西不起作用:

ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.mainConstraint);
ConstraintSet set = new ConstraintSet();
set.clone(layout);

ImageView view = new ImageView(this);
layout.addView(view,0);
set.connect(view.getId(), ConstraintSet.TOP, layout.getId(), ConstraintSet.TOP, 60);
set.applyTo(layout);

ImageView甚至没有出现在布局上。当添加到RelativeLayout时,它就像一个魅力。

我可以做些什么来创建我需要的约束,以便我的布局再次工作?

java android android-layout android-constraintlayout
1个回答
54
投票

我认为你应该在添加ImageView后克隆布局。

ConstraintLayout layout = (ConstraintLayout)findViewById(R.id.mainConstraint);
ConstraintSet set = new ConstraintSet();

ImageView view = new ImageView(this);
view.setId(View.generateViewId());
layout.addView(view,0);
set.clone(layout);
set.connect(view.getId(), ConstraintSet.TOP, layout.getId(), ConstraintSet.TOP, 60);
set.applyTo(layout);
© www.soinside.com 2019 - 2024. All rights reserved.