【问题标题】:ConstraintLayout: Add UI elements programmaticallyConstraintLayout:以编程方式添加 UI 元素
【发布时间】:2018-10-26 05:53:45
【问题描述】:

我正在尝试在 ConstraintLayout 中的 现有 XML 定义的 ImageView 下方动态添加 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);

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

【问题讨论】:

  • 您需要以编程方式添加约束集。
  • 为什么我不能使用 ConstraintLayout.LayoutParams?我听说 ConstraintLayout.LayoutParams 和 ConstraintSet 都可以用来动态添加到 ConstraintLayouts,但是使用 LayoutParams 效率更高,因为它不需要为所有视图克隆整个现有布局。
  • 当您以编程方式从头开始构建时可以使用参数,但您已经拥有一个视图!所以使用 ConstraintSet。

标签: java android android-constraintlayout


【解决方案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

【讨论】:

  • 我试过这个,但结果相同。另外,为什么要将 LayoutParams 与 ConstraintSet 混合使用?不应该是其中一个吗?
猜你喜欢
  • 1970-01-01
  • 2018-07-08
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
相关资源
最近更新 更多