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();
|