在Android中获得布局膨胀器的正确方法是什么?

2022-09-01 07:46:17

有一种方法可以使布局更平坦:

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

另一种方法是:

LayoutInflater inflater = LayoutInflater.from(context);

第三个(当我在活动中时)是:

LayoutInflater inflater = getLayoutInflater();

那么它们之间有什么区别呢?

请注意,当我将第三个充气机发送到我的适配器时,我的应用程序正常工作。但是,当我发送上下文并通过第二种方式创建充气机时,它没有!


答案 1

在活动之外使用

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

在您的活动中

     LayoutInflater inflater = getLayoutInflater();

检查此

如果你打开 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;
    }

并且没有区别

只要调用的活动或窗口具有与 调用 相同的上下文,就没有区别。getLayoutInflater()getSystemService()


答案 2

它们之间没有太大的区别。

正如文档所说,公共抽象对象获取系统服务(字符串名称)

用于在此上下文中膨胀布局资源的布局增量。

对于公共静态布局从(上下文上下文)

从给定上下文获取布局默认值。

你可以检查这个线程 getLayoutInflater() 和 .getSystemService(Context.LAYOUT_INFLATER_SERVICE) 之间有什么区别吗?


推荐