LayoutParams 填充应用于父视图,但边距应用于子视图

LayoutParams padding applied to parent View but margin to child

我有两个嵌套的 LinearLayouts - 水平列表的垂直列表(我正在尝试制作调色板选择器)。

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)

但现在发生的情况是,Padding 应用于 Parent LinearLayout,而 margin 应用于 LinearLayoutRow。正如您在图像中看到的那样,行之间有一点 space,但是父容器应用了巨大的 50dp 填充。 我不明白这种行为。 this 是扩展的 class class ColorPalettePicker(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {}

填充不是 LayoutParams 的一部分。因此,当您调用 setPadding() 时,它实际上是在调用父级的 setPadding()。你应该这样称呼它

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

其实里面的方法setpadding apply 并不会影响LayoutParams 它是为parent view 设置的。设置 magins 会影响您创建的参数,这意味着它会影响子视图