首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >安卓: View.inflate和getLayoutInflater().inflate有什么区别?

安卓: View.inflate和getLayoutInflater().inflate有什么区别?
EN

Stack Overflow用户
提问于 2016-02-22 08:22:20
回答 2查看 2.2K关注 0票数 5

在以下方面有什么真正的区别:

代码语言:javascript
复制
return context.getLayoutInflater().inflate(R.layout.my_layout, null);

从指定的xml资源中膨胀新的视图层次结构。

代码语言:javascript
复制
return View.inflate(context, R.layout.my_layout, null);

从XML资源中膨胀视图。这个方便的方法封装了LayoutInflater类,它为视图膨胀提供了一系列的选项。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-22 08:32:48

两者是一样的。第二个版本只是一个方便和简短的方法来完成这项任务。如果您看到View.inflate()方法的源代码,您会发现:

代码语言:javascript
复制
 /**
     * 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);
    }

它实际上在后端执行相同的工作,您提到的第一种方法就是这样做的。

票数 6
EN

Stack Overflow用户

发布于 2016-02-22 08:35:25

他们是一样的,做同样的事情。

View.java类中

代码语言:javascript
复制
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

LayoutInflater.from(context)返回LayoutInflator对象。这与调用getLayoutInflator()方法相同。

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35548844

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档