在实际开发种LayoutInflater这个类还是非常有用的,它的作用类似于findViewById(),
不同点是LayoutInflater是用来找layout下xml布局文件,并且实例化!而findViewById()是找具体xml下的具体widget控件(如:Button,TextView等)。
为了让大家容易理解我做了一个简单的Demo,主布局main.xml里有一个TextView和一个Button,当点击Button,出现Dialog,而这个Dialog的布局方式是我们在layout目录下定义的custom_dialog.xml文件(里面左右分布,左边ImageView,右边TextView)。
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:id="@+id/textview" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button" android:text="inflater" /> </LinearLayout>
再新建一个自定义的layout的:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/imageview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp"/> <TextView android:id="@+id/tview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#F0F" android:text="image" /> </LinearLayout>
MainActivity.java如下:
package com.example.androidinflatertest; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.view.LayoutInflater; import android.view.Menu; 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 { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)findViewById(R.id.button); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub showCustomerDialog(); } private void showCustomerDialog() { // TODO Auto-generated method stub AlertDialog.Builder builder; AlertDialog alertdialog; Context context=MainActivity.this; LayoutInflater inflater=(LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE); View layout=inflater.inflate(R.layout.custom_dialog, null); TextView text=(TextView)layout.findViewById(R.id.tview); ImageView image=(ImageView)layout.findViewById(R.id.imageview); image.setImageResource(R.drawable.ia); builder=new AlertDialog.Builder(context); builder.setView(layout); alertdialog=builder.create(); alertdialog.show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
运行结果: