Adapter是连接后端数据和前端显示的适配器接口,适配器是数据和视图之间的桥梁。
在常见的View(ListView,GridView)等地方都需要用到Adapter。android提供的
三种Adapter主要有ArrayAdapter,SimpleAdapter,SimpleCursorAdapter。
其中ArrayAdapter的构造方法参数有多种,在使用时一般用如下两种,分别有三个、四个参数:
(1)ArrayAdapter<String>(context, textViewResourceId, objects)
(2)ArrayAdapter<String>(context, resource, textViewResourceId, objects)
官方对参数的解释是:
-
Parameters:
- context The current context.
- resource The resource ID for a layout file containing a layout to use when instantiating views.
- textViewResourceId The id of the TextView within the layout resource to be populated
- objects The objects to represent in the ListView.
- 其实resource 主要就是layout的布局,也就是哪个XML布局文件
-
textViewResourceId 主要就是布局文件下的TextView
下面看一下两者之间的使用区别:
(1)ArrayAdapter<String>(this, R.layout.list_item_1, objects)
(2)ArrayAdapter<String>(this,R.layout.list_item_2,R.id.lv,objects)
list_item_1:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
list_item_2:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
可以发现三参数中的textViewResourceId,直接用一个只含有TextView
的布局文件即可,且不能用含有LinearLayout布局的条目。四参数中的textViewResourceId则使用resource布局文件下id=lv的TextView。