【发布时间】: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