在代碼中動態創建水平 LinearLayout,包含標題文本、左側「連接」按鈕、右側「斷開」按鈕,要求兩按鈕分別靠左、靠右對齊。
關鍵在於給中間佔位的 TextView 設置 layout_weight="1" 並靠左,或使用 Space 佔位。以下是兩種實現方式:
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
// 標題
TextView titleView = new TextView(this);
titleView.setText("Hallo Welt!");
titleView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(titleView);
// 中間彈性空間(關鍵)
View spacer = new View(this);
LinearLayout.LayoutParams spacerParams = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
spacer.setLayoutParams(spacerParams);
layout.addView(spacer);
// 左側按鈕
Button btnConnect = new Button(this);
btnConnect.setText("Connect");
btnConnect.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(btnConnect);
// 右側按鈕
Button btnDisconnect = new Button(this);
btnDisconnect.setText("Disconnect");
btnDisconnect.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(btnDisconnect);
若需精確控制邊距、對齊基線,建議改用 RelativeLayout:
RelativeLayout rl = new RelativeLayout(this);
rl.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
Button btnConnect = new Button(this);
btnConnect.setId(View.generateViewId());
btnConnect.setText("Connect");
RelativeLayout.LayoutParams lpConnect = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lpConnect.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rl.addView(btnConnect, lpConnect);
Button btnDisconnect = new Button(this);
btnDisconnect.setText("Disconnect");
RelativeLayout.LayoutParams lpDisconnect = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lpDisconnect.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rl.addView(btnDisconnect, lpDisconnect);
LayoutParams,否則默認 WRAP_CONTENT 導致擠壓。gravity 作用於 View 內部內容對齊,layout_gravity 作用於 View 在父容器中的對齊,切勿混淆。View.generateViewId() 動態生成唯一 ID,便於 RelativeLayout 規則引用。掌握 layout_weight 與 RelativeLayout 規則,動態佈局不再是難題。