在一般项目中使用adapter时,加载item布局咱们一般会使用:
LayoutInflater.from(context).inflate(R.layout.list_item,
比如这样一个item布局:
<</span>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" >
<</span>TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView1" />
<</span>TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView2" />
</</span>LinearLayout>
html] view plaincopy
- android:layout_height="50dp"
-
android:layout_margin="50dp"
这是一个老外对inflate()的研究。
第一个参数无需过多解释。
第二个参数指的是加载布局的root
Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (ifattachToRoot is false.)
大概就是说如果后面attachToRoot为true的情况下,这个布局会被解析并加载在root下面,如果为false,则会依照root去解析该xml并返回view,但是这个view不会被加载到root里。
其实如果为false,就是讲xml解析了,并依照root的类型给生成的view set一个LayoutParams
然后咱们看源代码里
- LayoutInflater.from(context).inflate(R.layout.list_item,
null);
- public
View inflate(int resource, ViewGroup root) { -
return inflate(resource, root, root != null); - }
- LayoutInflater.from(context).inflate(R.layout.list_item,root,false);
然后再在listview的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; - }
发现在listview里加载item的布局,
- android:layout_height="50dp"
这是因为在listview里,convertview用的是viewgroup的
为了验证一下,咱们在linearlayout中实验一下LayoutInflater
- layout=(LinearLayout)findViewById(R.id.layout1);
- View
view=LayoutInflater.from(this).inflate(R.layout.list_item,layout , false); -
layout.addView(view);
奥,对了,注意,在listview中不要将inflate(int resource, ViewGroup root, boolean attachToRoot)的attachToRoot设为true,
因为这样等于说让listview addview(convertView),但是listview不能加子控件,会报如下错误:
- java.lang.UnsupportedOperationExce
ption: addView(View, LayoutParams) is not supported in AdapterView
而在linearlayout里可以将inflate(int resource, ViewGroup root, boolean attachToRoot)的attachToRoot设为true,这样就相当于
- View
view=LayoutInflater.from(this).inflate(R.layout.list_item,layout , false); -
layout.addView(view);
最后附上demo下载地址http://download.csdn.NET/detail/ccfcccfc/8142913点击打开链接
转自:http://blog.sina.com.cn/s/blog_7d95a2e70102v9xr.html,thanks!