基于Android LayoutInflater的使用介紹
在android中,LayoutInflater有點(diǎn)類似于Activity的findViewById(id),不同的是LayoutInflater是用來找layout下的xml布局文件,并且實(shí)例化!而findViewById()是找具體xml下的具體 widget控件(如:Button,TextView等)。
下面通過一個例子進(jìn)行詳細(xì)說明:
1、在res/layout文件夾下,添加一個xml文件dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/diaimage"
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
</ImageView>
<TextView
android:id="@+id/diatv"
android:layout_width="wrap_content"
android:layout_height="fill_parent" />
</LinearLayout>
2、在main.xml文件中添加一個按鈕,此按鈕用于實(shí)現(xiàn)點(diǎn)擊顯示一個Dialog
<Button
android:id="@+id/btnshowdialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Dialog" />
3、在MainActivity的onCreate方法中添加如下代碼,實(shí)現(xiàn)具體功能操作
Button showdialog = (Button) findViewById(R.id.btnshowdialog);
showdialog.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
AlertDialog dialog;
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog, null);
TextView diatv = (TextView) layout.findViewById(R.id.diatv);
diatv.setText("Welcome to LayoutInflater study");
ImageView image = (ImageView) layout.findViewById(R.id.diaimage);
image.setImageResource(R.drawable.ic_launcher);
builder.setView(layout);// <--important,設(shè)置對話框內(nèi)容的View
dialog = builder.create();
dialog.show();
}
});
運(yùn)行程序,點(diǎn)擊按鈕,將實(shí)現(xiàn)如下效果!

相關(guān)文章
mac開發(fā)android環(huán)境搭建步驟圖解
這里比較詳細(xì)的來總結(jié)下mac開發(fā)android的環(huán)境搭建步驟安裝過程,希望對一些正準(zhǔn)備配置Android開發(fā)環(huán)境的小伙伴們有一定幫助2014-01-01
Android中ProgressBar用法簡單實(shí)例
這篇文章主要介紹了Android中ProgressBar用法,以簡單實(shí)例形式分析了Android中ProgressBar進(jìn)度條控件的功能與布局相關(guān)技巧,需要的朋友可以參考下2016-01-01
深入android中The connection to adb is
本篇文章是對android中The connection to adb is down的問題以及解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
Android無限循環(huán)RecyclerView的完美實(shí)現(xiàn)方案
這篇文章主要介紹了Android無限循環(huán)RecyclerView的完美實(shí)現(xiàn)方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06

