(1)数组适配器(ArrayAdapter)
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(context, textViewResourceId, objects)
context:上下文对象,一般填this即可
textViewResourceId:每个Item的布局样式,可以直接使用android提供的(例如:android.R.layout.simple_list_item_1
),如果android提供的不满足你的需求,你也可以自己写一个Layout
objects:数据源, 一般为一个数组或集合
实例:
MainActivity.java
public class MainActivity extends Activity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, new String[] { "Item1",
"Item2", "Item3", "Item4", "Item5" });
listView.setAdapter(adapter);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
(2)简单适配器(SimpleAdapter)
它虽然叫简单适配器,其实它还是比较复杂的
SimpleAdapter adapter = new SimpleAdapter(context, data, resource, from, to);
context:上下文对象,一般填this即可
data: 数据源,一般为List包装的Map
resource:每个Item的布局样式
from: 一个String的数组,里面包含Map中的键名
to:绑定数据视图的中的ID,与from成对应的关系
实例:
MainActivity.java
public class MainActivity extends Activity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
SimpleAdapter adapter = new SimpleAdapter(this, getData(),
R.layout.item_layout, new String[] { "img", "text" },
new int[] { R.id.iv, R.id.tv });
listView.setAdapter(adapter);
}
//数据源
private List<Map<String, Object>> getData() {
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
for (int i = 0; i <= 5; i++) {
Map<String, Object> map = new ArrayMap<String, Object>();
map.put("img", R.drawable.ic_launcher);
map.put("text", "Item" + i);
data.add(map);
}
return data;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
item_layout.xml
<?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="horizontal" >
<ImageView
android:id="@+id/iv"
android:layout_width="60dp"
android:layout_height="60dp"/>
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:textSize="40sp"/>
</LinearLayout>
注意:from 和 to 一定要是一一对应的
(3)基本适配器(BaseAdapter)
* 以后再更新*