【问题标题】:Why should I use LayoutInflater to obtain a view if I can directly obtain it using findViewById()如果可以直接使用 findViewById() 获取视图,为什么还要使用 LayoutInflater 获取视图
【发布时间】:2015-11-10 15:43:21
【问题描述】:

我是android开发的初学者,很难理解Inflater的使用。我已经阅读了这个问题:

What does it mean to inflate a view from an xml file?

现在考虑这个例子:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
                               (ViewGroup) findViewById(R.id.toast_layout_root));
Toast toast = new Toast(getApplicationContext());
toast.setView(layout);
toast.show();

据我了解,我们使用 inflater 将 xml 布局膨胀(转换)为 View 对象,然后我们使用 setView(layout) 设置视图。 但是,如果我们只需要设置 toast 的视图,那么为什么不简单地使用 findviewbyid 如下:

Toast toast=new Toast(this);
toast.setView(findViewById(R.id.toast_layout_root));
toast.setDuration(toast.LENGTH_LONG);
toast.show();

上面的代码可以编译,但它会导致应用程序在启动时崩溃。我知道这样做是错误的,但为什么呢?

使用inflater得到的view和使用findViewById得到的view有什么区别。

【问题讨论】:

  • 使用inflater以编程方式创建视图,使用findViewById从已经创建并调整大小的当前窗口中抓取视图。
  • 我预计两者都会崩溃,抱怨 View 已经有一个父级。

标签: android layout-inflater


【解决方案1】:

这不是一回事。

Inflate 获取一个 Layout xml 文件并从中生成一个视图。

findViewById 在 vi​​ewGroup 中查找视图。

在你的例子中:

您的第一个代码将膨胀 R.layout.custom_toast 并将其附加到父 ViewGroup R.id.toast_layout_root

您的第二个代码将采用 R.id.toast_layout_root ViewGroup 并将其设置为对话框的布局。

基本上,您的第一个代码将以R.layout.custom_toast 作为对话框布局,而您的第二个代码将使用R.id.toast_layout_root 作为对话框布局。

这显然不是一回事,findViewById 需要一个已经膨胀的视图。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-08-05
    • 1970-01-01
    • 2014-05-22
    • 2013-12-28
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    相关资源
    最近更新 更多