Android数据填充器LayoutInflater
LayoutInflater类在应用程序中比较实用,可以叫布局填充器,也可以成为打气筒,意思就是将布局文件填充到自己想要的位置,LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化这个XML文件成为一个View,有点类似于类似于findViewById(),但是findViewById()是找xml布局文件下的具体widget控件(Button、TextView)。对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;对于一个已经载入的界面,使用Activiyt.findViewById()方法来获得其中的界面元素。
LayoutInflater实例方式
首先简单看下三种简单的实例方式:
1
2
3
|
LayoutInflater layoutInflater = getLayoutInflater(); LayoutInflater layoutInflater2 = LayoutInflater.from( this );
LayoutInflater layoutInflater3 = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
|
第一种getLayoutInflater方式:
1
2
3
|
public LayoutInflater getLayoutInflater() {
return getWindow().getLayoutInflater();
}
|
第二种实现方式:
1
2
3
4
5
6
7
8
|
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null ) {
throw new AssertionError( "LayoutInflater not found." );
}
return LayoutInflater;
} |
后两种调用的都是getSystemService,第一种也是~
LayoutInflater实现Demo
LayOutInflater填充布局的时候有四种方法,Demo使用第一种:
resource:需要加载布局文件的id,需要将这个布局文件中加载到Activity中来操作。
root:inflate()会返回一个View对象如果root不为null,就将这个root作为根对象返回,作为这个xml文件的根视图,如果是null,那么这个xml文件本身就是一个根视图:
1
2
3
4
5
6
|
public View inflate ( int resource, ViewGroup root)
public View inflate (XmlPullParser parser, ViewGroup root)
public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)
public View inflate ( int resource, ViewGroup root, boolean attachToRoot)
|
看下实现的结果:
在主窗体中定义一个按钮,这个代码就不贴了~直接写点击事件的处理吧:
定义一个Item文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?xml version= "1.0" encoding= "utf-8" ?>
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:id= "@+id/test"
android:layout_width= "match_parent"
android:layout_height= "match_parent"
android:orientation= "vertical" >
<TextView
android:id= "@+id/inflate_txt"
android:layout_width= "match_parent"
android:layout_height= "match_parent"
android:text= "测试" />
</LinearLayout> |
点击事件的处理:
1
2
3
4
5
6
7
8
9
10
|
LayoutInflater layoutInflater = getLayoutInflater(); View view = layoutInflater.inflate(R.layout.item, null );
TextView text = (TextView) view.findViewById(R.id.inflate_txt); text.setText( "http://www.cnblogs.com/xiaofeixiang" );
text.setTextSize( 18 );
text.setTextColor(Color.RED); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity. this );
builder.setView(view); AlertDialog alertDialog = builder.create(); alertDialog.show(); |
本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/4060705.html,如需转载请自行联系原作者