Android加载xml布局文件方法
2014-02-08 11:27
260 查看
我们常常会遇到这样的情况,函数setContentView(R.layout.XXX);指定一个xml文件作为该Activity的布局文件,这样,如果我们要操作该xml文件中的Button、ImageView、TextView等组件,就可以直接用:Button btn = (Button) findViewById(R.id.button);这样是可以的,但是如果我们要操作的这些组件并不在setContentView函数里面指定的xml文件中,这个时候再用上面的方法就会报空指针错误。所以我们要用到inflater,LayoutInflater的作用是将layout文件下的xml文件实例化为View对象,即调用inflate方法将xml文件转成View。
获取LayoutInflater的方法有如下三种:
查看第二种方法的源码,实质上和第一种是一样。
转自:http://blog.csdn.net/cool_oyty/article/details/9849339
获取LayoutInflater的方法有如下三种:
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = LayoutInflater.from(context); View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.main, null);
查看第二种方法的源码,实质上和第一种是一样。
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; }
转自:http://blog.csdn.net/cool_oyty/article/details/9849339
相关文章推荐
- Android 根据不同的屏幕,加载不同的布局文件 使用refs.xml
- Android 加载Assets目录中Xml布局文件
- android使用include加载其他xml文件中的布局
- Android学习笔记-Android非布局activity中布局文件及控件加载方法
- android使用include加载其他xml文件中的布局
- Android View 动态加载不同xml布局文件
- android 动态设置横竖屏切换 控制dialog等布局文件加载的方法
- Android--使用LayoutInflater加载布局文件的三种方法
- android界面xml文件中导入另一个xml文件的方法include
- Android布局文件layout.xml的一些属性值
- Android中xml布局文件
- Androiid 如何动态加载assets目录下的xml布局文件(包括Drawable xml)
- android---xml---include用法(导入另一个XML文件到本布局中)
- Android中measure过程、WRAP_CONTENT详解以及xml布局文件解析流程浅析(上)
- Android中measure过程、WRAP_CONTENT详解以及xml布局文件解析流程浅析(下)
- android:scaleType 布局文件加载图片时候的显示方式
- Android布局文件layout.xml的一些属性值
- 编写XML布局文件及加载XML资源
- Android 在xml布局配置文件中给Button按钮添加事件
- android---xml---include用法(导入另一个XML文件到本布局中)