第二个实例:
下面的一个简单的LayoutInflater应用实例,主布局main.xml里有一个TextView和一个Button,当点击Button,出现 Dialog,而这个Dialog的布局方式是我们在layout目录下定义的dialog.xml文件(里面左右分布,左边 ImageView,右边TextView)。
main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- <Button
- android:id="@+id/btn"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="打开对话框"
- />
- </LinearLayout>
dialog.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="horizontal"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- >
- <ImageView
- android:id="@+id/img"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
- <TextView
- android:id="@+id/dialog_txt"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="测试LayoutInflater"
- />
- </LinearLayout>
MainActivity.java
- package com.lingdududu.test;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.os.Bundle;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ImageView;
- import android.widget.TextView;
- public class MainActivity extends Activity {
- private Button showBtn;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- showBtn = (Button)findViewById(R.id.btn);
- showBtn.setOnClickListener(new showDialogListener());
- }
- class showDialogListener implements OnClickListener{
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- showDialog();
- }
- }
- public void showDialog() {
- AlertDialog.Builder builder;
- AlertDialog dialog ;
- LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
- //LayoutInflater inflater = getLayoutInflater();
- //LayoutInflater inflater = LayoutInflater.from(this);
- View layout = inflater.inflate(R.layout.dialog, null);
- TextView tx = (TextView)layout.findViewById(R.id.dialog_txt);
- tx.setText("测试LayoutInflater");
- ImageView img = (ImageView)layout.findViewById(R.id.img);
- img.setImageResource(R.drawable.icon);
- builder = new AlertDialog.Builder(this);
- builder.setView(layout);
- dialog = builder.create();
- dialog.show();
- }
- }
效果图:

