1.界面布局文件XML中添加了一个ListView,代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ListView
android:id="@+id/ListViewID"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
2.接下来到MainActivity.java文件中实现数据添加等操作。public class MainActivity extends Activity {
//定义一个数组来保存所有水果的名字
private String[] names=new String[]{"苹果","榴莲","猕猴桃","橙子","菠萝","西瓜"};
//定义一个数组来保存所有水果的图片资源
private int[] images=new int[]{R.drawable.apple,R.drawable.jackfruit,R.drawable.kiwifruit,
R.drawable.orange,R.drawable.pineapple,R.drawable.watermelon};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建一个List集合
List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
for (int i = 0; i < names.length; i++) {
Map<String, Object> map=new HashMap<String, Object>();
map.put("name", names[i]);
map.put("image", images[i]);
list.add(map);
}
//创建一个SimpleAdapter
String[] from=new String[]{"name","image"};
int[] to=new int[]{R.id.textviewID,R.id.imageID};
SimpleAdapter adapter=new SimpleAdapter(this, list, R.layout.simple_list_item, from, to);
ListView listView=(ListView) findViewById(R.id.ListViewID);
listView.setAdapter(adapter);
}
创建SimpleAdapter时需要5个参数,第1个就不说了,第2个参数应该是一个List<? extends Map<String ?>>类型的集合对象,该集合中每个Map<String ?>对象生成一个列表项。
第3个参数指定一个界面布局的ID(列表项的布局文件)。
第4个参数是一个String[]类型的参数,该参数决定提取Map<String ?>对象中哪些Key对应的value来生成列表项。
第5个参数是一个int[]类型的参数,该参数决定要填充哪些组件。
3.自定义的item布局simple_list_item代码如下:<?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/imageID"
android:layout_width="48dp"
android:layout_height="48dp" />
<TextView
android:id="@+id/textviewID"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:gravity="center" />
</LinearLayout>
最终运行效果如下:
4.ListView的点击事件:
如果需要监听Listview的点击和选中事件,则可以使用AdapterView的listView.setOnItemClickListener();【短按】
listView.setOnItemLongClickListener();【长按】listView.setOnItemSelectedListener();【选中】方法来添加监听器。
代码如下:
//为ListView的列表项添加短按事件监听器
listView.setOnItemClickListener(new OnItemClickListener() {
//点击列表项时执行该方法
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//此处吐司被点击的列表项的名字
Toast.makeText(MainActivity.this, names[position], Toast.LENGTH_SHORT).show();
}
});
再次运行效果如下: