我以编程方式创建了一个 ImageView ,并将其添加到约束布局中。现在我想在 imageView 的左侧和右侧添加边距。
这就是我所做的。
ImageView imageView = new ImageView(this);
imageView.setId(View.generateViewId());
constraintLayout.addView(imageView);
//Convert DP to PX
int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
10,
getResources().getDisplayMetrics());
//Loading image from URL by using Picasso.
Picasso.with(getApplicationContext())
.load(imageURL)
.placeholder(R.drawable.card_loading)
.fit()
.centerCrop()
.into(imageView);
imageView.setAdjustViewBounds(true);
//Created Constraint Set.
ConstraintSet set = new ConstraintSet();
set.clone(constraintLayout);
set.constrainWidth(imageView.getId(), ConstraintSet.MATCH_CONSTRAINT);
set.connect(imageView.getId(), ConstraintSet.TOP, eventsViewPager.getId(), ConstraintSet.BOTTOM, margin);
set.connect(imageView.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, margin);
set.connect(imageView.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, margin);
现在的问题是它从顶部创建了边距,但没有从左侧和右侧添加边距。
最佳答案
尝试使用 ConstraintSet.START
和 ConstraintSet.END
而不是 ConstraintSet.LEFT
和 ConstraintSet.RIGHT
。这应该可以解决您的问题。
关于android - 如何以编程方式在约束布局中添加左右边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49632376/