Android的LayoutInflater的使用

  LayoutInflater的功能就是从layout文件夹中找xml文件,然后实例化。


  比方说我们要自定义一个对话框的内容和布局。那么我们的LayoutInflater就能派上用场了。


  activity_main.xml文件如下:

<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="hello">   <button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ShowCustomDialog">    </button></textview></linearlayout>


  LayoutInflater.java文件如下:

package com.example.layoutinflater; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.ImageView; public class LayoutInflaterDemo extends Activity implements OnClickListener { private Button button; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.button); button.setOnClickListener(this); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub showCustomDialog(); } public void showCustomDialog() { AlertDialog.Builder builder; AlertDialog alertDialog; Context mContext = LayoutInflaterDemo.this; //下面俩种方法都可以 //方法一:LayoutInflaterinflater = getLayoutInflater(); //方法二: LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.custom_dialog, null); TextView text = (TextView)layout.findViewById(R.id.text); text.setText("Hello, I am Pocoyo Shamoo"); ImageView image = (ImageView)layout.findViewById(R.id.image); image.setImageResource(R.drawable.ic_launcher); builder = new AlertDialog.Builder(mContext); builder.setView(layout); alertDialog = builder.create(); alertDialog.show(); } }


 显示的自定义对话框的布局文件custom_dialog.xml如下:



<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp">    <imageview android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginright="10dp">    <textview android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textcolor="#FFF">    </textview></imageview></linearlayout>

你可能感兴趣的:(Android的LayoutInflater的使用)