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

问题描述

我在以编程方式将视图添加到 ConstraintLayout 并设置布局工作所需的所有约束时遇到问题.

I'm having a problem to programmatically add views to a ConstraintLayout, 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 parentLayout = (ConstraintLayout)findViewById(R.id.mainConstraint);
    ConstraintSet set = new ConstraintSet();

    ImageView childView = new ImageView(this);
    // set view id, else getId() returns -1
    childView.setId(View.generateViewId());
    parentLayout.addView(childView, 0);

    set.clone(parentLayout);
    // connect start and end point of views, in this case top of child to top of parent.
    set.connect(childView.getId(), ConstraintSet.TOP, parentLayout.getId(), ConstraintSet.TOP, 60);
    // ... similarly add other constraints
    set.applyTo(parentLayout);

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

08-05 23:09