android - 如何以编程方式在约束布局中添加左右边距

标签 android android-layout constraints android-constraintlayout

我以编程方式创建了一个 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.STARTConstraintSet.END 而不是 ConstraintSet.LEFTConstraintSet.RIGHT 。这应该可以解决您的问题。

关于android - 如何以编程方式在约束布局中添加左右边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49632376/

相关文章:

java - 在textview Android中显示秒数倒计时

android - 单击 AlertDialog 项目列表时在 RecyclerView 布局之间切换

iOS - 如何设置约束,使标签的底部等于 ImageView ,但高度可以变化

java - 安卓测试 : Can I send sms to the emulator number from test method?

android - 用户更改方向后,网站无法正确显示全屏背景

android - android如何为不同的api级别选择资源文件夹

android - 如何在布局的中心准确显示 Switch 小部件?

android - 以与用户手指在布局上移动相同的速度更改相对布局的高度

mysql - 从具有外键约束的 MySQL 表中删除

c# - 更改呈现 View Controller 约束