【问题标题】:What is the difference between calling LayoutInflater directly and not?直接调用和不调用 LayoutInflater 有什么区别?
【发布时间】:2012-06-02 08:24:15
【问题描述】:

我浏览了一些教程,在 Android Doc 中,它说在实例化 LayoutInflater 时不要直接访问它。来自谷歌文档的示例:

LayoutInflater inflater = (LayoutInflater)context.getSystemService
  (Context.LAYOUT_INFLATER_SERVICE);

我经历的教程是这个:

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

所以我真的不明白除了明显不同的代码之外还有什么区别。任何解释都非常感谢。我认为 Android Doc 应该是我们遵循的那个,但我不确定它是否会有所作为。

【问题讨论】:

    标签: android layout-inflater


    【解决方案1】:

    如果你打开 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 方法很好,因为它需要的输入更少,就是这样。

    【讨论】:

    • 哈哈!哇谢谢!这真的很有帮助。我会有另一个问题,但你甚至回答了那个问题。非常感谢!
    【解决方案2】:
    LayoutInflater inflater = (LayoutInflater)context.getSystemService
      (Context.LAYOUT_INFLATER_SERVICE);
    

    你从System Manager得到LayoutInflater Service Provider

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

    您正在使用来自LayoutInflater Classstatic 方法

    我会说差异仅在于代码以及您如何编写此代码以及调用堆栈,但结果相同 - 您将获得 LayoutInflater

    更多关于this

    问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-26
      • 2013-07-22
      • 2013-09-01
      • 2014-05-02
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 2011-09-08
      相关资源
      最近更新 更多