LayoutInflater
LayoutInflater的作用
LayoutInflater这的作用类似于findViewById()。不同点是:
LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化为View类对象。对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素,因为在一个Activity里对应的是setConentView()的那个layout里的组件。
通俗的说,inflate就相当于将一个xml中定义的布局找出来。因此如果你的Activity里如果用到别的layout,比如对话框上的layout,你还要设置对话框上的layout里的组件(像图片ImageView,文字TextView)上的内容,你就必须用inflate()先将对话框上的layout找出来,然后再用这个layout对象去找到它上面的组件,所以对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入。
获得 LayoutInflater 实例的三种方式
|
LayoutInflater inflater = getLayoutInflater();//调用Activity的getLayoutInflater() LayoutInflater inflater = LayoutInflater.from(context); LayoutInflater inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE); |
四种加载方式
|
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) |
示意代码:
|
View view = LayoutInflater.from(mContext).inflate(R.layout. pic_layout, null, false); LinearLayout forward = (LinearLayout)view.findViewById(R.id. pic_bottom_layout); TextView textView = (TextView) left_convertView.findViewById(R.id.chat_time); |
浙公网安备 33010602011771号