直接调用LayoutInflater有什么区别?

And*_*ndy 9 android layout-inflater

我浏览了一些教程,在Android Doc中,它说在实例化时不直接访问LayoutInflater.来自Google Doc的示例:

LayoutInflater inflater = (LayoutInflater)context.getSystemService
  (Context.LAYOUT_INFLATER_SERVICE);
Run Code Online (Sandbox Code Playgroud)

我经历的教程就是这个:

LayoutInflater inflater = LayoutInflater.from(parent.getContext());
Run Code Online (Sandbox Code Playgroud)

所以除了显而易见的不同代码之外,我真正理解的不同之处在于.任何解释都非常感激.我假设Android Doc应该是我们遵循的那个,但我不确定它是否有所作为.

sat*_*ine 17

如果您打开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;
}
Run Code Online (Sandbox Code Playgroud)

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