可以使用LayoutParams来动态设置LinearLayout的子项的边距。示例如下:
LinearLayout layout = findViewById(R.id.layout);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
layoutParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
TextView textView = new TextView(this);
textView.setText("Dynamic margin");
layout.addView(textView, layoutParams);
其中,setMargins方法接收四个参数,即左边距(leftMargin)、上边距(topMargin)、右边距(rightMargin)、下边距(bottomMargin)。可以根据实际需求来设置这四个参数。
在这个示例中,我们创建了一个LinearLayout,并通过LayoutParams设置了TextView的边距。最后将TextView添加到LinearLayout中显示。