ConstraintLayout: Добавить элементы пользовательского интерфейса программно - PullRequest
0 голосов
/ 26 октября 2018

Я пытаюсь динамически добавить новый ImageView ниже существующего XML-определенного ImageView в ConstraintLayout:

    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 голосов
/ 26 октября 2018

Попробуйте этот код:

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);

Проверьте больше из здесь .

Примечание здесь: Длясоздание ограничений во время выполнения с использованием ConstraintSet.

...