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

前端之家收集整理的这篇文章主要介绍了调用LayoutInflater直接而不是有什么区别?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我经历了一些教程,在 Android文档中,它表示在实例化时不直接访问LayoutInflater.来自Google Doc的示例:
  1. LayoutInflater inflater = (LayoutInflater)context.getSystemService
  2. (Context.LAYOUT_INFLATER_SERVICE);

我经历的教程是这样的:

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

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

解决方法

如果您打开Android源代码,您可以看到LayoutInflator.from方法如下所示:
  1. /**
  2. * Obtains the LayoutInflater from the given context.
  3. */
  4. public static LayoutInflater from(Context context) {
  5. LayoutInflater LayoutInflater =
  6. (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  7. if (LayoutInflater == null) {
  8. throw new AssertionError("LayoutInflater not found.");
  9. }
  10. return LayoutInflater;
  11. }

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

猜你在找的Android相关文章