1. 程式人生 > >Android使用LayoutInflater動態載入佈局和操作控制元件

Android使用LayoutInflater動態載入佈局和操作控制元件

我們知道在Android中通過佈局檔案來描述軟體的介面,而通常在Activity中都是使用setContentView()來將佈局顯示出來。但是如果我們在非Activity的情況下,而且需要對佈局中的控制元件進行設定等操作,該如何處理呢?這就需要使用到動態載入佈局 LayoutInflater,下面ATAAW.COM來做介紹。

  以一個簡單佈局example.xml為例,裡面只有一個按鈕和一個文字顯示框控制元件。

  < TextView

  android:id="@+id/tview"

  android:layout_width="fill_parent"

  android:layout_height="wrap_content"

  android:text="ATAAW.COM"

  />

  < Button

  android:layout_width="fill_parent"

  android:layout_height="wrap_content"

  android:id="@+id/button"

  android:text="按鈕"

  />

  在程式中動態載入以上佈局。

  LayoutInflater flater = LayoutInflater.from(this);

  View view = flater.inflate(R.layout.example, null);

  獲取佈局中的控制元件。

  button = (Button) view.findViewById(R.id.button);

  textView = (TextView)view.findViewById(R.id.tview);

  為Button新增事件監聽。

  button.setOnClickListener(new OnClickListener(){

  @Override

  public void onClick(View v) {

  textView.setText("WWW.ATAAW.COM");

  }

  });

  一般情況下,LayoutInflater在定義介面卡中使用的比較多,例如我們可以為介面卡定義佈局,繼而在介面卡的設計中對控制元件進行資料繫結等設定操作。