Android LayoutInflater詳解
作用:
1、對于一個沒有被載入或者想要動態載入的界面, 都需要使用inflate來載入.
2、對于一個已經載入的Activity, 就可以使用實現了這個Activiyt的的findViewById方法來獲得其中的界面元素.
方法:
Android里面想要創建一個畫面的時候, 初學一般都是新建一個類, 繼承Activity基類, 然后在onCreate里面使用setContentView方法來載入一個在xml里定義好的界面.
其實在Activity里面就使用了LayoutInflater來載入界面, 通過getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法可以獲得一個 LayoutInflater, 也可以通過LayoutInflater inflater = getLayoutInflater();來獲得.然后使用inflate方法來載入layout的xml,
首先我們要知道,什么是已經被載入的layout,什么是還沒有載入的.我們啟動一個應用,與入口Activity相關的layout{常見的是 main.xml}就是被載入的,即在Oncreate()中的.而其他的layout是沒有被載入的.就要動態載入了或通過另一個activity.
在實際開發種LayoutInflater這個類還是非常有用的,它的作用類似于 findViewById(),
不同點是LayoutInflater是用來找layout下xml布局文件,并且實例化!而findViewById()是找具體xml下的具體 widget控件.
為了讓大家容易理解我[轉]做了一個簡單的Demo,主布局main.xml里有一個TextView和一個Button,當點擊Button,出現 Dialog,而這個Dialog的布局方式是我們在layout目錄下定義的custom_dialog.xml文件(里面左右分布,左邊 ImageView,右邊TextView)。
在實際開發種LayoutInflater這個類還是非常有用的,它的作用類似于findViewById(),不同點是 LayoutInflater是用來找layout下xml布局文件,并且實例化!而findViewById()是找具體xml下的具體widget控件(如:Button,TextView等)。
主布局main.xml里有一個TextView和一個Button,當點擊Button,出現Dialog,而這個Dialog的布局方式是我們在layout目錄下定義的custom_dialog.xml文件(里面左右分布,左邊ImageView,右邊TextView)。
XML代碼:
<?xmlversion="1.0"encoding="utf-8"?>定義對話框的布局方式,我們在layout目錄下,新建一個名為custom_dialog.xml文件具體代碼如下:
XML代碼:
<?xmlversion="1.0"encoding="utf-8"?>
主程序LayouInflaterDemo.java代碼如下:
packageEOE.android.Demo;importandroid.app.Activity;
importandroid.app.AlertDialog;
importandroid.content.Context;
importandroid.os.Bundle;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.ImageView;
importandroid.widget.TextView;
publicclassLayoutInflaterDemoextendsActivityimplementsOnClickListener{
privateButtonbutton;
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
publicvoidonClick(Viewv){
showCustomDialog();
}
publicvoidshowCustomDialog(){
AlertDialog.Builderbuilder;
AlertDialogalertDialog;
ContextmContext=LayoutInflaterDemo.this;
//下面倆種方法都可以
////LayoutInflaterinflater=getLayoutInflater();
LayoutInflaterinflater=(LayoutInflater)mContext.getSystemServic(LAYOUT_INFLATER_SERVICE);
Viewlayout=inflater.inflate(R.layout.custom_dialog,null);
TextViewtext=(TextView)layout.findViewById(R.id.text);
text.setText("Hello,WelcometoMrWei'sblog!");
ImageViewimage=(ImageView)layout.findViewById(R.id.image);
image.setImageResource(R.drawable.icon);
builder=newAlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog=builder.create();
alertDialog.show();
}
} </pre>