在實際開發中LayoutInflater這個類還是非常有用的,它的作用類似於findViewById()。不同點是LayoutInflater是用來找res/layout/下的xml布局檔案,並且執行個體化;而findViewById()是找xml布局檔案下的具體widget控制項(如Button、TextView等)。
具體作用:
1、對於一個沒有被載入或者想要動態載入的介面,都需要使用LayoutInflater.inflate()來載入;
2、對於一個已經載入的介面,就可以使用Activiyt.findViewById()方法來獲得其中的介面元素。
在使用時候有三種方法:
//LayoutInflater inflater = LayoutInflater.from(context);
//LayoutInflater inflater=getLayoutInflater();
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
請看下面的詳細代碼:注意在onCreate方法裡面
Button btn = new Button(this);
btn.setText("點擊載入");
//LayoutInflater inflater = LayoutInflater.from(this);
//LayoutInflater inflater=getLayoutInflater();
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.activity_main, null);
view.addView(btn);
setContentView(view);//設定當前的布局為view
ProgressDialog的用法:
有兩種:1.重寫Activitiy裡面的onCreateDialog,
但調用的時候,使用Activity的showDialog(0);
public Dialog onCreateDialog(int id) {
ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("進度條");//設定標題
pd.setCancelable(true);//設定是否可以按回退鍵取消
pd.setIndeterminate(true);//設定為不明確
pd.setMessage("正在運行...");//設定內容
return pd;
}
2.直接建立出來
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//showDialog(0);
ProgressDialog.show(MainActivity.this, "進度條", "正在載入,請稍等...",true,true);
}
});