Android使用LayoutInflater動態載入佈局和操作控制元件
以一個簡單佈局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在定義介面卡中使用的比較多,例如我們可以為介面卡定義佈局,繼而在介面卡的設計中對控制元件進行資料繫結等設定操作。