0

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

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
babuntu
  • 27
  • 8

2 Answers2

1

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)
Ismail Shaikh
  • 482
  • 4
  • 13
  • Thank you. can you explain why it doesnt show an error? .apply should call it on the LayoutParams so if it doesnt have such a member function is should throw an error? – babuntu May 06 '20 at 13:49
  • 1
    its like when you call a method in an inner class. if the inner class doesn't have a method you are calling then the outer class method is called. – Ismail Shaikh May 06 '20 at 14:52
1

Actually method setpadding inside apply not affect to LayoutParams it is set for parent view. Set magins is affect to your params you create it mean it affect child view

Công Hải
  • 4,961
  • 3
  • 14
  • 20