微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

调用LayoutInflater直接而不是有什么区别?

我经历了一些教程,在 Android文档中,它表示在实例化时不直接访问LayoutInflater.来自Google Doc的示例:
LayoutInflater inflater = (LayoutInflater)context.getSystemService
  (Context.LAYOUT_INFLATER_SERVICE);

我经历的教程是这样的:

LayoutInflater inflater = LayoutInflater.from(parent.getContext());

所以我不太明白的是除了明显不同的代码之外还有什么区别.任何解释非常感谢.我认为Android文档应该是我们遵循的,但我不知道是否有所作为.

解决方法

如果您打开Android源代码,您可以看到LayoutInflator.from方法如下所示:
/**
 * 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;
}

这意味着你的问题中的两行代码做同样的事情.不知道你阅读的教程是什么,但是我没有看到任何功能的差异.使用from方法是很好的,因为它需要一点点打字,就是这样.

原文地址:https://www.jb51.cc/android/311678.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐