為每個動態建立的 Button 建立 LinearLayout.LayoutParams,呼叫 setMargins(left, top, right, bottom) 設定四周間距。
LinearLayout container = findViewById(R.id.button_container);
container.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < 5; i++) {
Button btn = new Button(this);
btn.setText("Button " + (i+1));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 20, 0, 0); // 上間距 20dp
btn.setLayoutParams(params);
container.addView(btn);
}
setMargins 參數單位為**像素**。若需 dp,請轉換:int marginPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics());RelativeLayout,使用 RelativeLayout.LayoutParams 並配合 addRule 定位。android:layout_margin 設定(靜態佈局)。