【问题标题】:Change the margin of a constraint layout programmatically [duplicate]以编程方式更改约束布局的边距[重复]
【发布时间】:2021-01-25 21:17:56
【问题描述】:

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

代码是:

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()
    }
  }

}

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

    item_store_product_layout.leftPadding = dip(0)

但它不适用于margin。

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

谢谢

【问题讨论】:

    标签: android kotlin android-constraintlayout layoutmargins


    【解决方案1】:

    Margins 与 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 2013-06-14
      相关资源
      最近更新 更多