Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 動態佈局入門:五大 Layout 的程式化組裝技巧

編輯:關於 Android 程式設計

動態佈局與靜態佈局各有適用場景。靜態佈局寫在 XML 中,結構一目了然、維護容易;動態佈局則完全以程式碼組出畫面,不必經過 XML 到程式碼的轉換,改動版面時機動性高,也方便直接銜接業務邏輯。

代價是程式碼量通常較大,可讀性與維護成本不如 XML。即便如此,掌握動態佈局的技巧在實務上仍常有幫助——例如元件數量需要依資料動態決定時。

基本三步驟

動態佈局的做法相當固定:先建立容器(五大 Layout)的物件,接著設定容器與子元件的屬性,最後把子元件加進容器。

以 RelativeLayout 為例

RelativeLayout mLayout = new RelativeLayout(this);

// LayoutParams 用來描述子元件在容器中的尺寸與位置。
// 每個 ViewGroup 都有一組對應的 LayoutParams。
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

// 建立子元件
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.tab_icon_conversation_normal);

// 設定子元件在 RelativeLayout 中的位置
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

// 把子元件與它的 LayoutParams 一起加入容器
mLayout.addView(iv, params);

最後一行說明了重點:params 描述的是 ImageView 的行為,而 addView 必須把 view 與 params 成對傳入,否則位置設定不會生效。

_absolute 與 Relative 的對照

絕對配置(AbsoluteLayout 在後續版本已被標記為不建議使用,此處僅作理解定位機制之用):

AbsoluteLayout abslayout = new AbsoluteLayout(this);
setContentView(abslayout);

Button btn1 = new Button(this);
btn1.setText("this is a button");
btn1.setId(1);

AbsoluteLayout.LayoutParams lp1 = new AbsoluteLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT,
        0, 100);

abslayout.addView(btn1, lp1);

相對配置:

RelativeLayout relativeLayout = new RelativeLayout(this);
setContentView(relativeLayout);

AbsoluteLayout abslayout = new AbsoluteLayout(this);

RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT);
lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);

relativeLayout.addView(abslayout, lp1);

線性配置與「動態加入整份 XML」

// 純程式碼建立
LinearLayout ll = new LinearLayout(this);
EditText et = new EditText(this);
ll.addView(et);

// 方法一:inflate 時直接指定父容器
LinearLayout ll = (LinearLayout) this.getLayoutInflater()
        .inflate(R.layout.main1, null);
setContentView(ll);
LinearLayout ll2 = (LinearLayout) this.getLayoutInflater()
        .inflate(R.layout.main2, ll);
// main2 會作為 main1 的子佈局,掛在根節點下

// 方法二:先 inflate 再用 addView 組裝
LinearLayout ll = (LinearLayout) this.getLayoutInflater()
        .inflate(R.layout.main1, null);
setContentView(ll);
LinearLayout ll2 = (LinearLayout) this.getLayoutInflater()
        .inflate(R.layout.main2, null);
ll.addView(ll2);

實務建議

動態佈局並非萬靈丹。元件的層級越深,效能負擔越大,特別是 RelativeLayout 巢狀與大量 LinearLayout 疊加時。若畫面結構固定,寫成 XML 通常更好維護;只有當元件數量、順序或樣式必須依執行期資料決定時,才值得全部用程式碼組。

另一個常見折衷做法是「XML 打底 + 程式碼補充」:主結構放在 XML,需要動態生成的部分用 LayoutInflater 載入小片段再插入,兼顧可讀性與彈性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved