ConstraintLayout:以编程方式添加UI元素

时间:2018-10-26 05:53:46

标签: java android android-constraintlayout

我试图在ConstraintLayout中的现有 XML定义的ImageView下动态添加 new ImageView:

    ConstraintLayout layout = (ConstraintLayout)findViewById(R.id.constraintLayout);

    ImageView imgAbove = (ImageView)findViewById(R.id.topItemImg);
    ImageView imgBelow = new ImageView(this);
    imgBelow.setBackgroundColor(Color.YELLOW);
    imgBelow.setId(View.generateViewId());

    ConstraintLayout.LayoutParams imgAboveLayout = (ConstraintLayout.LayoutParams) imgAbove.getLayoutParams();
    ConstraintLayout.LayoutParams imgBelowLayout = new ConstraintLayout.LayoutParams(imgAboveLayout);

    imgBelowLayout.topToBottom = imgAbove.getId();
    imgAboveLayout.bottomToTop = imgBelow.getId();

    layout.addView(imgBelow);
    imgBelow.setLayoutParams(imgBelowLayout);
    imgAbove.setLayoutParams(imgAboveLayout);

但是,这会将新视图置于现有视图之上,以便它们完全重叠。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

ConstraintLayout layout = (ConstraintLayout)findViewById(R.id.constraintLayout);

ImageView imgAbove = (ImageView)findViewById(R.id.topItemImg);
ImageView imgBelow = new ImageView(this);
imgBelow.setBackgroundColor(Color.YELLOW);
imgBelow.setId(View.generateViewId());

ConstraintLayout.LayoutParams imgAboveLayout = (ConstraintLayout.LayoutParams) imgAbove.getLayoutParams();
ConstraintLayout.LayoutParams imgBelowLayout = new ConstraintLayout.LayoutParams(imgAboveLayout);
layout.addView(imgBelow);
imgBelow.setLayoutParams(imgBelowLayout);
imgAbove.setLayoutParams(imgAboveLayout);

// Clone your constraint layout to ConstraintSet.
ConstraintSet set = new ConstraintSet();
set.clone(layout);
set.connect(imgBelow.getId(), ConstraintSet.TOP, imgAbove.getId(), ConstraintSet.BOTTOM, 0);
set.connect(imgBelow.getId(), ConstraintSet.START, imgAbove.getId(), ConstraintSet.START, 0);
set.connect(imgBelow.getId(), ConstraintSet.END, imgAbove.getId(), ConstraintSet.END, 0);
set.applyTo(layout);

here中查看更多内容。

  

此处注意: 要在运行时建立约束,建议使用 ConstraintSet