LayoutInflater可以动态载入界面,在开发过程中是经常会使用到的一个类。下面是开发文档中对这个类的解释:
可以看到有两个参数,分别是resource和root,其中resource 是我们想进行实例化的xml文件的id,而关于root的解释请看http://blog.csdn.net/xpsharp/article/details/7165679
Instantiates a layout XML file into its corresponding View
objects. It is never used directly. Instead, use getLayoutInflater()
or getSystemService(String)
to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on.
即LayoutInflater可以讲一个layout的xml文件实例化,我们需要通过getLayoutInflater()或者getSystemService(String)方法来得到一个LayoutInflater实例,得到这个实例后我们可以通过相应的方法来实例化一个xml文件。以下是最常用的方法:
public View inflate (int resource, ViewGroup root)
Added in API level 1
Inflate a new view hierarchy from the specified xml resource. Throws InflateException
if there is an error.
Parameters
resource | ID for an XML layout resource to load (e.g., R.layout.main_page ) |
---|---|
root | Optional view to be the parent of the generated hierarchy. |
Returns
- The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.
下面是一个小的demo,方便理解
package com.xidian.layoutinflater;
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 btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
LayoutInflater inflater = getLayoutInflater();
final View another = inflater.inflate(R.layout.another, null);
TextView tv = (TextView)another.findViewById(R.id.tv);
ImageView img = (ImageView)another.findViewById(R.id.img);
tv.setText("第二个布局");
img.setImageResource(R.drawable.ic_launcher);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setView(another)
.show();
}
});
}
}
another xml文件:
<?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/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
</LinearLayout>
效果图: