竹山一叶

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

项目中用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" >
<TextViewandroid:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView1" />
<TextViewandroid:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView2" /></LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

如果你的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;  
}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

运行效果: 
这里写图片描述 
我们发现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);  
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

最终运行效果会发现 
android:layout_height, android:layout_margin都已经有效果了。






posted on 2017-04-18 11:33  竹山一叶  阅读(5477)  评论(0编辑  收藏  举报