Android 把XML定义的控件动态实例化

来源:互联网 发布:手机数字键盘钢琴软件 编辑:程序博客网 时间:2024/06/03 15:49

我们在添加视图文件的时候有两种方式,一种是通过在xml文件定义layout,另一种方式是在java代码中动态生成布局文件。

在xml中定义的layout要想转化为view,需要使用到LayoutInflater类。

1.构造xml文件

2.LayoutInflater

提到addview,首先要了解一下LayoutInflater类。这个类最主要的功能就是实现将xml表述的layout转化为View的功能。为了便于理解,我们可以将它与findViewById()作一比较,二者都是实例化某一对象,不同的是findViewById()是找xml布局文件下的具体widget控件实例化,而LayoutInflater找res/layout/下的xml布局文件来实例化的。

(1)创建

LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);或

LayoutInflater inflater = LayoutInflater.from(Activity.this);或

LayoutInflater inflater = getLayoutInflater();

这三种方法本质是相同的。

(2)inflate()

用LayoutInflater.inflate() 将LayOut文件转化成VIew。

View viewParent= inflater.inflate(R.layout.xx, null);

3.控件实例

View View=viewParent.findviewbyid(R.id.XX);

0 0