indViewById() 方法用于在一個(gè)已經(jīng)載入的界面(如 MainActivity)中獲取界面元素的方法凌唬,那么在一個(gè)沒(méi)有被載入或者需要被動(dòng)態(tài)載入的界面(如 Fragment )中需要獲得某個(gè)控件時(shí)霞捡,就需要用到 inflater 中的方法了。
首先勾哩,在一段 Fragment 代碼中進(jìn)行 Activity 式的 findViewById 獲取控件時(shí)宏邮,出現(xiàn)了空指針的錯(cuò)誤。經(jīng)過(guò)查找后纠拔,發(fā)現(xiàn)能用
View view = getActivity().getLayoutInflater().inflate(R.layout.dialogfragment,null);
spinner1 = view.findViewById(R.id.punish);
的方法獲取某個(gè)控件秉剑。再查看API,尋找具體的方法說(shuō)明稠诲。
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.
大概意思是說(shuō),在 view 中如果要獲取某個(gè) XML 文件的實(shí)例臀叙,需要用 getLayoutInflater() 略水,即用此方法獲得一個(gè) LayoutInflater 的對(duì)象。
然后劝萤,在該布局文件對(duì)象的基礎(chǔ)上渊涝,調(diào)用 inflater 的構(gòu)造方法
inflater(int resource, ViewGroup root, boolean attachToRoot)
inflater(int resource, null)
來(lái)將布局找出來(lái)。
resource:需要加載布局文件的id
root:要附加到 resource 上的資源文件的根控件
attachToRoot:是否將 root 附加到布局文件的根視圖上
以上,就解決了在一個(gè)動(dòng)態(tài)界面載入某個(gè)控件的問(wèn)題了跨释,先獲得對(duì)應(yīng)的布局對(duì)象胸私,再用 inflater 中的方法獲得布局,于是就可以獲得這個(gè)動(dòng)態(tài)載入界面的控件了鳖谈。