1、ArrayAdapter
// 匹配布局文件中的ListView控件
listView = (ListView) findViewById(R.id.listView);
// 数据适配器的定义
String[] data = new String[] { "java", "C++", "JavaScript", "Php",
"Python" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_list_item_1, data);
// 给ListView设置数据适配器
listView.setAdapter(adapter);
其中android.R.layout.simple_list_item_1是android系统自带的listitem
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
/>
2、SimpleAdapter
private ListView listView;
private SimpleAdapter simple_adapter;
private List<Map<String, Object>> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 匹配布局文件中的ListView控件
listView = (ListView) findViewById(R.id.listView);
getData();
// 设置SimpleAdapter监听器
simple_adapter = new SimpleAdapter(MainActivity.this,
list, R.layout.list_item,
new String[] { "image", "text" }, new int[] { R.id.image,
R.id.text });
listView.setAdapter(simple_adapter);
}
// 加载SimpleAdapter数据集
private List<Map<String, Object>> getData() {
list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("text", "java");
map.put("image", R.drawable.ic_launcher);
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("text", "C++");
map2.put("image", R.drawable.ic_launcher);
Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("text", "JavaScript");
map3.put("image", R.drawable.ic_launcher);
Map<String, Object> map4 = new HashMap<String, Object>();
map4.put("text", "Php");
map4.put("image", R.drawable.ic_launcher);
Map<String, Object> map5 = new HashMap<String, Object>();
map5.put("text", "Python2");
map5.put("image", R.drawable.ic_launcher);
list.add(map);
list.add(map2);
list.add(map3);
list.add(map4);
list.add(map5);
Log.i("Main", list.size() + "");
return list;
}
list_item.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:gravity="center_vertical"
android:orientation="horizontal" >
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textSize="25sp" />
</LinearLayout>