Home > OS >  Setting the marginStart on a MaterialCheckBox programmically doesn't set the margins
Setting the marginStart on a MaterialCheckBox programmically doesn't set the margins

Time:09-22

AS 2020.3.1

Trying to programmatically set the start margin on a MaterialCheckBox that I am programmatically adding to a layout.

This is my layout:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@ id/list_item_category_item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@ id/llCategories"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

And this is the snippet of code I am using to set the margins

mapOfCategoryFilters.value.forEach { childCategoryItem ->
    val chkChildCategory = MaterialCheckBox(context)
    chkChildCategory.setTextColor(ContextCompat.getColor(context, R.color.black))
    chkChildCategory.text = childCategoryItem.label

    val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
    layoutParams.setMargins(32, 0, 0, 0)
    chkChildCategory.layoutParams = layoutParams
    llCategories.addView(chkChildCategory)
}

I have also tried the following which didn't work.

val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
layoutParams.setMargins(32, 0, 0, 0)
llCategories.addView(chkChildCategory, layoutParams)

The reason I need to set programmatically, as I would to indent some based on a condition.

enter image description here

CodePudding user response:

Try

val layoutParams = LinearLayoutCompat.LayoutParams(
                   ViewGroup.LayoutParams.MATCH_PARENT,
                   ViewGroup.LayoutParams.WRAP_CONTENT)

You are using LinearLayout.LayoutParams.

  • Related