在写Android程序时,有时候会编写自定义的View,使用Inflater对象来将布局文件解析成一个View。本文主要目的是总结获取LayoutInflater对象的方法。


1、若能获取context对象,可以有以下几种方法:

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);View child = inflater.inflate(R.layout.child, null);

or

LayoutInflater inflater = LayoutInflater.from(context);View child = inflater.inflate(R.layout.child, null);
</pre><p></p><pre>
2、在一个Activity中,可以有以下方法:

View child = getLayoutInflater().inflate(R.layout.child, item, false);
or

View view; LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.mylayout, null);

方法1和方法2其实都是对context().getSystemService()的使用


3、使用View的静态方法:

View view=View.inflate(context, R.layout.child, null)

inflate实现源码如下:

    /**     * Inflate a view from an XML resource.  This convenience method wraps the {@link     * LayoutInflater} class, which provides a full range of options for view inflation.     *     * @param context The Context object for your activity or application.     * @param resource The resource ID to inflate     * @param root A view group that will be the parent.  Used to properly inflate the     * layout_* parameters.     * @see LayoutInflater     */    public static View inflate(Context context, int resource, ViewGroup root) {        LayoutInflater factory = LayoutInflater.from(context);        return factory.inflate(resource, root);    }
LayoutInflater.from(context)实际上是对方法1的包装,可参考以下源码:

    /**     * Obtains the LayoutInflater from the given context.     */    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;    }




更多相关文章

  1. Rxjava的基础用法和源码解析(一)
  2. Android(安卓)Junit Test
  3. Android(安卓)JsBridge源码学习
  4. Android(安卓)刷新页面更新数据方法探究
  5. Android中怎么动态控制padding
  6. Android类参考---Fragment
  7. Android(安卓)纯代码加入点击效果
  8. Android(安卓)中TextView中跑马灯效果的实现方法
  9. Android开发之去掉title的三种方法

随机推荐

  1. mysql遇到load data导入文件数据出现1290
  2. Mysql指定日期区间的提取方法
  3. mysql 8.0.11 macos10.13安装配置方法图
  4. mysql 5.6.23 安装配置环境变量教程
  5. Ubuntu16.04安装mysql5.7.22的图文教程
  6. 浅析mysql.data.dll驱动各版本介绍
  7. Mysql数据库实现多字段过滤的方法
  8. MySQL入门(五) MySQL中的索引详讲
  9. MySQL入门(四) 数据表的数据插入、更新、
  10. MySQL入门(三) 数据库表的查询操作【重要