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

我目前无法使用:

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

我该怎么做才能创建所需的约束,以便重新进行布局?

最佳答案

我认为您应该在添加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());
    layout.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);

08-04 01:07