1

我创建了许多视图使用的约束布局,但在特定视图中,我需要修改边距,但找不到最佳方法。

代码是:

class BundleItemView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

  init {
    View.inflate(context, R.layout.item_product, this)
  }

  fun setProduct(product: Product) {
    /* change margin to 0 for this constraint layout */
    item_store_product_layout.leftPadding = dip(0)
    product_image.setImageURI(ImageUtil.getCellImageWithFallback(product))
    product_name.text = product.completeTitle
    product_sub_name_1.text = product.prettySizeString
    product_add_button.text = context.getString(R.string.view_details)

    product_regular_price_label.visibility = View.GONE
    product_regular_price_value.visibility = View.GONE
    product_price.setPrice(product.originalPrice)

    product_add_button.onClick {
      Toast.makeText(context, product.completeTitle, Toast.LENGTH_SHORT).show()
    }
  }

}

所以当我 infalte 时item_product.xml,我想修改布局。我已经使用以下命令更改了左侧填充:

    item_store_product_layout.leftPadding = dip(0)

但它不起作用margin

知道如何以编程方式更改约束布局的边距吗?

谢谢

4

1 回答 1

2

边距与View相关联,但属于ViewGroup,在您的情况下,它是ConstraintLayout。在ConstraintLayout.LayoutParams中进行边距更改

// view is the view to change margins for
val lp = view.layoutParams as ConstraintLayout.LayoutParams
lp.leftMargin = 200 // change to 200px
lp.topMargin = 200
lp.rightMargin = 200
lp.bottomMargin = 200
view.requestLayout() // May or may not be needed depending upon where the code is placed.

如果要更改连接,也可以使用ConstraintSet在ConstraintLayout中设置边距。

val cs = ConstraintSet()
cs.clone(layout) // layout is the ConstraintLayout
cs.connect(
    R.id.textView,
    ConstraintSet.START,
    ConstraintSet.PARENT_ID,
    ConstraintSet.START,
    200 // Start margins is now 200px
)
cs.applyTo(layout)

您正在将某些小部件的可见性设置为,View.GONE以便您可以使用Gone Margins

于 2021-01-26T13:29:56.017 回答