【问题标题】:Is there any difference between getLayoutInflater() and .getSystemService(Context.LAYOUT_INFLATER_SERVICE)getLayoutInflater() 和 .getSystemService(Context.LAYOUT_INFLATER_SERVICE) 之间有什么区别吗
【发布时间】:2012-08-21 08:58:15
【问题描述】:

简单的“不”回答会让我平静下来。 如果有什么不同,那是什么?

【问题讨论】:

    标签: android android-layout android-widget


    【解决方案1】:

    没有

    只要调用getLayoutInflater() 的Activity 或Window 与调用getSystemService() 的上下文相同,就没有区别。


    证明你可以追踪getLayoutInflater()返回的LayoutInflater到LayoutInflater.from(),你可以从源代码中看到这只是getSystemService()的一个快捷方式:

    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;
    }
    

    【讨论】:

      【解决方案2】:

      至少有一种情况只有

      getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      必须用来代替对应物

      getLayoutInflater

      这种情况是在任意对象类中。例如,我有一个类调用 objectA 的实例。在 objectA 中,我想将视图膨胀到父视图上(发生在 ArrayAdapter 中,它会膨胀其列表视图上的自定义行。)在这种情况下,context.getLayoutInflater 不会工作,因为没有与上下文相关的活动或窗口。只有 getSystemService(Context.LAYOUT_INFLATER_SERVICE) 是合适的。

      【讨论】:

        【解决方案3】:

        这就是您定义 LayoutInflater 的方式。

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

        getLayoutInflater() 只是通过返回 LayoutInflater 来“快速访问窗口从其上下文中检索到的 LayoutInflater 实例”(来自documentation)。

        同样,getSystemService(Context.LAYOUT_INFLATER_SERVICE) 用于检索 LayoutInflater 以在此上下文中膨胀布局资源。

        所以,实际上两者之间存在 NO 区别。

        来源:Documentation

        【讨论】:

          【解决方案4】:

          没有。

          完全没有区别。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-09-13
            • 2017-04-05
            • 2014-09-18
            • 2015-06-14
            • 2011-05-23
            相关资源
            最近更新 更多