1. LayoutInflater有什么用
可以将一个Layout文档(Android中使用XML文档来描述一个Layout)实例化为一个View的实例。
This class is used to instantiate layout XML file into its corresponding View objects . It is never be used directly -- use getLayoutInflater() or getSystemService(String)getLayoutInflater() or getSystemService(String) 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.
一个最简单的应用例子。我们在创建一个Activity的时候,一般会为该Activity设定一个内容视图,如 setContentView(R.layout.main)
我们可以看看setContentView的文档:
void android.app.Activity.setContentView(int layoutResID)
Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity. Parameters layoutResID Resource ID to be inflated.
意思是我们设定内容视图时,实际就是inflate了一个layout文件。即如上所说,将XML文档实例化为一个View的实例(Layout中描述的所有控件都会被实例化为View,一般返回的是Root View,就是最根本的View句柄)。
2. LayoutInflater与findViewById的区别
实际上弄清楚了setContentView做的事情,就比较容易理解两者的区别。
findViewById是用来查找当前Activity对应layout中的某项View,使用了R.Id.XXX作为参数来索引。也就是说,要先inflate了一个layout,再用findViewById来找layout实例中的某项View。
再具体一点,setContentView实例化了一个layout(当然也可以用LayoutInflater.inflate())来做),findViewById找其中的某项View。
View android.app.Activity.findViewById(int id)
Finds a view that was identified by the id attribute from the XML that was processed in onCreate (Bundle). Returns the view if found or null otherwise.
以上除去标注为引用的部分,其余为自己组织的语言。
如果需要实例,可以参考http://shazhuzhu1.iteye.com/blog/985815