LayoutInflater基础

来源:互联网 发布:mac版魔兽世界插件 编辑:程序博客网 时间:2024/04/27 21:19
 

LayoutInflater 在 android 开发中使用频率较高,今天谈谈!
该类是一个抽象类,在文档中如下声明:

view plaincopy to clipboardprint?
  1. public abstract class LayoutInflater extends Object  
1.  获得 LayoutInflater 实例
三种方法可以获得该实例对象,方法如下:
view plaincopy to clipboardprint?
  1. a. LayoutInflater inflater = getLayoutInflater();  
  2.   
  3.   
  4. b. LayoutInflater localinflater =  
  5.         (LayoutInflater)context.getSystemService  
  6.             (Context.LAYOUT_INFLATER_SERVICE);   
  7.   
  8.   
  9. c. LayoutInflater inflater = LayoutInflater.from(context);  
对于方法 a,主要是调用 Activity 的 getLayoutInflater() 方法。继续跟踪研究 android 源码,Activity 中的该方法是调用 PhoneWindow 的
getLayoutInflater()方法,那么,分享一下该源代码:
view plaincopy to clipboardprint?
  1. public PhoneWindow(Context context) {  
  2.         super(context);  
  3.         mLayoutInflater = LayoutInflater.from(context);  
  4. }<span style="font-family: Arial, Verdana, sans-serif; white-space: normal; "> </span>  
可以看出它其实是调用 LayoutInflater.from(context),那么该方法其实是调用 b,看看源码,如下:
view plaincopy to clipboardprint?
  1. /** 
  2.     * Obtains the LayoutInflater from the given context. 
  3.     */  
  4.    public static LayoutInflater from(Context context) {  
  5.        LayoutInflater LayoutInflater =  
  6.                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  7.        if (LayoutInflater == null) {  
  8.            throw new AssertionError("LayoutInflater not found.");  
  9.        }  
  10.        return LayoutInflater;  
  11.    }  
2. inflate 方法
inflate 愿意是充气之类的,在这里主要意思就是,扩张、使之膨胀。换句话说就是将当前视图view 补充完整、扩展该视图。
通过 sdk 的 api 文档,可以知道该方法有以下几种过载形式,返回值均是 View 对象,如下:
view plaincopy to clipboardprint?
  1. public View inflate (int resource, ViewGroup root)  
  2.   
  3.   
  4. public View inflate (XmlPullParser parser, ViewGroup root)  
  5.   
  6.   
  7. public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)  
  8.   
  9.   
  10. public View inflate (int resource, ViewGroup root, boolean attachToRoot)  
示意代码:
view plaincopy to clipboardprint?
  1. LayoutInflater inflater = (LayoutInflater)  
  2.     getSystemService(LAYOUT_INFLATER_SERVICE);  
  3.   
  4.   
  5. /* R.id.test 是 custom.xml 中根(root)布局 LinearLayout 的 id */  
  6. View view = inflater.inflate(R.layout.custom,  
  7.          (ViewGroup)findViewById(R.id.test));  
  8. /* 通过该 view 实例化 EditText对象, 否则报错,因为当前视图不是custom.xml.即没有 setContentView(R.layout.custom) 或者 addView() */  
  9. //EditText editText = (EditText)findViewById(R.id.content);// error  
  10. EditText editText = (EditText)view.findViewById(R.id.content);  
对于上面代码,指定了第二个参数 ViewGroup root,当然你也可以设置为 null 值。


注意:该方法与 findViewById 方法不同。inflater 是用来找 layout 下 xml 布局文件,并且实例化!而 findViewById() 是找具体 xml 下的具体 widget 控件(如:Button,TextView 等)。


更多关于 inflate 方法,请看 LayoutInflater 源码。

原创粉丝点击