现在的位置: 首页 > 综合 > 正文

View 编程(0): 认识 LayoutInflater

2012年10月30日 ⁄ 综合 ⁄ 共 1935字 ⁄ 字号 评论关闭

LayoutInflater 在 android 开发中使用频率较高,需要留意!


该类是一个抽象类,在文档中如下声明:


public abstract class LayoutInflater extends Object


1.  获得 LayoutInflater 实例

三种方法可以获得该实例对象,方法如下:


a. LayoutInflater inflater = getLayoutInflater();

b. LayoutInflater localinflater =
  (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE); 

c. LayoutInflater inflater = LayoutInflater.from(context);


对于方法 a,主要是调用 Activity 的 getLayoutInflater() 方法。


继续跟踪研究 android 源码,Activity 中的该方法是调用 PhoneWindow 的 getLayoutInflater()方法!


那么,分享一下该源代码:


public PhoneWindow(Context context) {
        super(context);
        mLayoutInflater = LayoutInflater.from(context);


可以看出它其实是调用 LayoutInflater.from(context), 那么该方法其实是调用 b,看看源码,如下:


   /**
     * Obtains the LayoutInflater from the given context.
     */

    public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;

    }


2. inflate 方法

inflate 愿意是充气之类的,在这里主要意思就是,扩张、使之膨胀。

换句话说就是将当前视图view 补充完整、扩展该视图。


通过 sdk 的 api 文档,可以知道该方法有以下几种过载形式,返回值均是 View 对象,如下:


public View inflate (int resource, ViewGroup root)

public View inflate (XmlPullParser parser, ViewGroup root)

public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)

public View inflate (int resource, ViewGroup root, boolean attachToRoot)


示例代码:


LayoutInflater inflater = (LayoutInflater)
getSystemService(LAYOUT_INFLATER_SERVICE);

/* R.id.test 是 custom.xml 中根(root)布局 LinearLayout 的 id */
View view = inflater.inflate(R.layout.custom,

(ViewGroup)findViewById(R.id.test));


/* 通过该 view 实例化 EditText对象, 否则报错,因为当前视图不是custom.xml.

即没有 setContentView(R.layout.custom) 或者 addView() */

//EditText editText = (EditText)findViewById(R.id.content);// error

EditText editText = (EditText)view.findViewById(R.id.content);


对于上面代码,指定了第二个参数 ViewGroup root,当然你也可以设置为 null 值。

注意:该方法与 findViewById 方法不同。

inflater 是用来找 layout 下 xml 布局文件,并且实例化!

而 findViewById() 是找具体 xml 下的具体 widget 控件(如: Button,TextView 等)。

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







抱歉!评论已关闭.