Android 如果可以使用findViewById()直接获取视图,为什么要使用LayoutInflater获取视图

Android 如果可以使用findViewById()直接获取视图,为什么要使用LayoutInflater获取视图,android,layout-inflater,Android,Layout Inflater,我是android开发的初学者,很难理解充气机的使用。我已经读过这个问题: 现在考虑这个例子: LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root)); Toast toast = new

我是android开发的初学者,很难理解充气机的使用。我已经读过这个问题:

现在考虑这个例子:

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();
据我所知,我们使用充气器将xml布局充气(转换)为视图对象,然后使用setView(layout)设置视图。 但如果我们只需要设置toast的视图,那么为什么不简单地使用findviewbyid,如下所示:

Toast toast=new Toast(this);
toast.setView(findViewById(R.id.toast_layout_root));
toast.setDuration(toast.LENGTH_LONG);
toast.show();
上面的代码可以编译,但会导致应用程序在启动时崩溃。我知道这样做是错误的,但为什么呢


使用充气机获得的视图与使用findViewById获得的视图有什么不同。

这不是一回事

Inflate获取一个布局xml文件并从中生成一个视图

findViewById在视图组中查找视图

在您的示例中:

您的第一个代码将膨胀
R.layout.custom\u toast
并将其附加到父视图组
R.id.toast\u layout\u root

第二个代码将采用
R.id.toast\u layout\u root
ViewGroup并将其设置为对话框的布局

基本上,第一个代码将以
R.layout.custom\u toast
作为对话框布局,而第二个代码将使用
R.id.toast\u layout\u root
作为对话框布局

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


希望这能有所帮助。

使用充气器以编程方式创建视图,使用findViewById从当前窗口获取视图,该窗口已经创建并调整大小。我预计两者都会崩溃,抱怨
视图已经有父视图。