indViewById() 方法用于在一个已经载入的界面(如 MainActivity)中获取界面元素的方法,那么在一个没有被载入或者需要被动态载入的界面(如 Fragment )中需要获得某个控件时,就需要用到 inflater 中的方法了。

首先,在一段 Fragment 代码中进行 Activity 式的 findViewById 获取控件时,出现了空指针的错误。经过查找后,发现能用

View view = getActivity().getLayoutInflater().inflate(R.layout.dialogfragment,null);

spinner1 = view.findViewById(R.id.punish);

的方法获取某个控件。再查看API,寻找具体的方法说明。

getLayoutInflater()

在文档中查找到 LayoutInflater 类,描述如下

Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use getLayoutInflater() or getSystemService(Class) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on.

大概意思是说,在 view 中如果要获取某个 XML 文件的实例,需要用 getLayoutInflater() ,即用此方法获得一个 LayoutInflater 的对象。

然后,在该布局文件对象的基础上,调用 inflater 的构造方法

inflater(int resource, ViewGroup root, boolean attachToRoot)

inflater(int resource, null)

来将布局找出来。

resource:需要加载布局文件的id

root:要附加到 resource 上的资源文件的根控件

attachToRoot:是否将 root 附加到布局文件的根视图上

以上,就解决了在一个动态界面载入某个控件的问题了,先获得对应的布局对象,再用 inflater 中的方法获得布局,于是就可以获得这个动态载入界面的控件了。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐