首页 > 学院 > 开发设计 > 正文

xml解析成view对象需要注意的事

2019-11-09 14:51:09
字体:
来源:转载
供稿:网友

        很多时候我们需要把一个xml布局文件转成view对象,通过以下代码实现:

    inflater.inflate(int resource, ViewGroup root, boolean attachToRoot);

其中inflater对象可以通过以下几种方式获取:

LayoutInflater inflater=LayoutInflater.from(Context context);LayoutInflater inflater=getLayoutInflater();LayoutInflater inflater=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);

inflate方法有几个重载 比如我们可以写成 inflater.inflate(int resource, null);当我们传入null时,跟布局layout_xxx属性无效,比如我要实现图下这种效果,通过添加item间的分隔来测试

                                       

  我们在item的xml中代码为

                      

看跟布局FramLayout中的 layout_margin="5dp" ,item间的分隔符是通过这个实现的,但是当我们解析xml文件的代码写成inflater.inflate(int resource, null);发现没有分隔效果,如下图

                                       

但是把layout_margin="5dp" 属性写在TextView中就有效果了,

通过查阅源码发现,当root也就是ViewGroup parent 这个参数不为空并且attachToRoot为false时 跟布局属性才被设置进去,

当然你可以选择把layout相关属性写在对应的子view中,但是如果子view太多就不便于代码的书写,这时候在跟布局中就比较好控制,

其实还有一种加载xml为view对象的写法 View.inflate(Context context,int resource, ViewGroup root),原理都是一样的,这种我们第三个参数一般为null,否则会报一个异常,这种跟上面差不多,当ViewGroup为null时,resource中的跟布局layout属性就无效了,所以还是推荐上面的加载xml布局的写法


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表