使用LayoutInflater動(dòng)態(tài)加載布局和操作控件
我們知道在Android中通過布局文件來描述軟件的界面,而通常在Activity中都是使用setContentView()來將布局顯示出來。但是如果我們?cè)诜茿ctivity的情況下,而且需要對(duì)布局中的控件進(jìn)行設(shè)置等操作,該如何處理呢?這就需要使用到動(dòng)態(tài)加載布局LayoutInflater,下面ATAAW.COM來做介紹。
以一個(gè)簡(jiǎn)單布局example.xml為例,里面只有一個(gè)按鈕和一個(gè)文本顯示框控件。
<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="按鈕"
/>
在程序中動(dòng)態(tài)加載以上布局。
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添加事件監(jiān)聽。
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
textView.setText("WWW.ATAAW.COM");
}
});
一般情況下,LayoutInflater在定義適配器中使用的比較多,例如我們可以為適配器定義布局,繼而在適配器的設(shè)計(jì)中對(duì)控件進(jìn)行數(shù)據(jù)綁定等設(shè)置操作。文章
?
鳳凰涅槃/浴火重生/馬不停蹄/只爭(zhēng)朝夕
???? 隱姓埋名/低調(diào)華麗/簡(jiǎn)單生活/完美人生
posted on 2010-10-29 13:02 poetguo 閱讀(4324) 評(píng)論(1) 編輯 收藏 所屬分類: Android