获得 LayoutInflater 实例

来源:互联网 发布:linux c函数库 chm 编辑:程序博客网 时间:2024/05/16 08:40

1.获得 LayoutInflater 实例的三种方法:
a. LayoutInflater inflater = getLayoutInflater();  b. LayoutInflater localinflater =          (LayoutInflater)context.getSystemService              (Context.LAYOUT_INFLATER_SERVICE);   c. LayoutInflater inflater = LayoutInflater.from(context); 
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 等)。






原创粉丝点击