【发布时间】: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已经有一个父级。