Search code examples
androidandroid-linearlayoutandroid-layoutparams

LayoutParams padding applied to parent View but margin to child


I have two nested LinearLayouts - A vertical list of horizontal Lists (im trying to make a Color Palette Picker).

val params = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT
        ).apply {
            val borderWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50f, resources.displayMetrics).toInt()
            setPadding(borderWidth, borderWidth, borderWidth, borderWidth)
            setMargins(0, 0, 0, 10)
        }
        LinearLayoutRow.layoutParams = params
        // add to to tree
        this.addView(LinearLayoutRow)

But what happens now is that the Padding is applied to the Parent LinearLayout while the margin is applied to the LinearLayoutRow. As you can see in the image there is a little space between the rows, but the huge 50dp padding is applied to the parent container. I dont understand that behaviour. this is by the way the extended class class ColorPalettePicker(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {} wrong padding


Solution

  • Padding is not a part of LayoutParams. so when you are calling setPadding() it is actually calling the setPadding() of the parent. you should call it like

    linearLayoutRow.setPadding(borderWidth, borderWidth, borderWidth, borderWidth)