基于Android LayoutInflater的使用介紹
在android中,LayoutInflater有點類似于Activity的findViewById(id),不同的是LayoutInflater是用來找layout下的xml布局文件,并且實例化!而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文件中添加一個按鈕,此按鈕用于實現(xiàn)點擊顯示一個Dialog
<Button
android:id="@+id/btnshowdialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Dialog" />
3、在MainActivity的onCreate方法中添加如下代碼,實現(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();
}
});
運行程序,點擊按鈕,將實現(xiàn)如下效果!
相關(guān)文章
解決webview內(nèi)的iframe中的事件不可用的問題
這篇文章主要介紹了解決webview內(nèi)的iframe中的事件不可用的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03Android中Fragment的分屏顯示處理橫豎屏顯示的實現(xiàn)方法
今天小編就為大家分享一篇關(guān)于Android中Fragment的分屏顯示處理橫豎屏顯示的實現(xiàn)方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03Android應(yīng)用開發(fā)中模擬按下HOME鍵的效果(實現(xiàn)代碼)
Android應(yīng)用開發(fā)中, 有一種場景,就是我們不希望用戶直接按Back鍵退出Activity,而是希望應(yīng)用隱藏到后臺,類似于按Home鍵的效果2013-05-05Android Messenger實現(xiàn)進(jìn)程間雙向通信
這篇文章主要為大家詳細(xì)介紹了Messenger實現(xiàn)進(jìn)程間雙向通信,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-05-05Android 快速使用正則表達(dá)式,校驗身份證號的實例
下面小編就為大家分享一篇Android 快速使用正則表達(dá)式,校驗身份證號的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01Android5.0以上版本錄屏實現(xiàn)代碼(完整代碼)
這篇文章主要介紹了Android5.0以上版本錄屏實現(xiàn)代碼,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2018-01-01