【问题标题】:How to add left and right margins in constraint layout programatically如何以编程方式在约束布局中添加左右边距
【发布时间】:2018-09-12 21:58:45
【问题描述】:

我以编程方式创建了一个图像视图,并将其添加到约束布局。现在我想在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); 

现在的问题是它从顶部创建边距,但没有从左右添加边距。

【问题讨论】:

    标签: android android-layout constraints android-constraintlayout


    【解决方案1】:

    尝试使用 ConstraintSet.STARTConstraintSet.END 而不是 ConstraintSet.LEFTConstraintSet.RIGHT 。这应该可以解决您的问题。

    【讨论】:

    • 谢谢 :) 这解决了问题
    • 我很高兴它有帮助:)
    • 最后别忘了打set.applyTo(...)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    相关资源
    最近更新 更多