您的位置:首页 > 其它

关于LayoutInflater的错误用法(警告提示:Avoid passing null as the view root)

2017-01-06 14:25 459 查看
项目中用LayoutInflater加载xml布局一直飘黄警告,上网搜了搜发现没有解释明白的,到是找到了一篇外国的博文,但是竟然是英文。。。幸好以前上学时候的英语不是很差加上谷歌的辅助,简单翻一下!

原文地址:http://www.cnblogs.com/kobe8/p/3859708.html

参考博客:http://blog.csdn.net/ccfcccfc/article/details/40984971

错误用法:

inflater.inflate(R.layout.my_layout, null);

加载xml布局常用的有这两个方法:

inflate(int resource, ViewGroup root)

resource:将要加载的xml布局

root:指定“将要加载的xml布局”的“根布局”

inflate(int resource, ViewGroup root, boolean attachToRoot)

attachToRoot:是否将解析xml生成的view加载到“根布局”中

注意:这里的参数root的设置很关键,会影响到xml解析生成的view;如果设置成null即没有指定“根布局”的话,xml的最外层根节点设置的android:layout_xxx等属性不会生效,因为android:layout_xxx等属性是在根布局中获得的;

第三个参数如果设置为:true,表示xml布局会被解析并加载到“根布局”中,如果为false,则会生成一个view并且不会加载到根布局中,但是这个view的类型取决于第二个参数根布局的类型,所以如果xml布局中设置了一些根布局类型中不存在的属性则不会有效果。下边是一个例子:

布局代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_margin="50dp"
android:gravity="center"
android:orientation="horizontal" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView1" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView2" />

</LinearLayout>


如果你的adapter中加载布局写成这样即不指定“根布局”:

LayoutInflater.from(context).inflate(R.layout.list_item, null);

运行效果



发现

android:layout_height=”50dp”

android:layout_margin=”50dp”

这两句代码没有效果,这是因为没有指定根布局,所以根布局里设置的android:layout_xxx等属性并没有起作用;

如果将adapter中加载布局代码改为:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(
R.layout.list_item, parent, false);
}

return convertView;
}


运行效果:



我们发现android:layout_height=”50dp” 已经有效果了

但是layout_margin没有起作用,这是因为我们上边设置的“根布局”是ViewGroup,他不能识别layout_margin属性,在线性布局里才会有这个属性。

如果将adapter中改为:

layout=(LinearLayout)findViewById(R.id.layout1);
View view=LayoutInflater.from(this).inflate(R.layout.list_item,layout , false);
layout.addView(view);


最终运行效果会发现

android:layout_height, android:layout_margin都已经有效果了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐