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

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

本文介绍了如何以编程方式将视图和约束添加到ConstraintLayout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having a problem to programmatically add views to a Constraint Layout, and set up all the constraints required for the layout to work.

我目前的工作不起作用:

What I have at the moment doesn't work:

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 时,它就像一个魅力。

The ImageView doesn't even appear on the layout. When adding to a RelativeLayout, it works like a charm.

我该怎么做才能创建我需要的约束,以便我的布局再次工作?

What can I do to create the constraints I need, so that my layout work again?

推荐答案

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

I think you should clone the layout after adding your ImageView.

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

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

这篇关于如何以编程方式将视图和约束添加到ConstraintLayout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:18