/*注意:1继承了ListActivity,ListActivity和普通的Activity没有太大的差别,
* 不同就是对显示ListView做了许多优化,方面显示而已
*2使用simpleAdapter的数据用一般都是HashMap构成的List,list的每一节对应ListView的每一行
*
*/
第一步:编写布局文件main.xml,添加一个imageview和textview。具体代码如下
View Code
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="horizontal"
4 android:layout_width="fill_parent"
5 android:layout_height="wrap_content">
6 <ImageView android:id="@+id/image"
7 android:layout_width="60dp"
8 android:layout_height="60dp"
9 android:src="@drawable/icon"
10 android:paddingLeft="10dp" />
11
12 <TextView android:id="@+id/textview1"
13 android:layout_width="wrap_content"
14 android:layout_height="fill_parent"
15 android:textSize="16dp"
16 android:gravity="center_vertical"
17 android:paddingLeft="10dp" />
18
19 </LinearLayout>
第三步:修改ListView03.java,添加listview的相关操作,具体代码如下
View Code
1 package cn.shaoyangjiang.com;
2
3 import java.util.ArrayList;
4 import java.util.HashMap;
5 import java.util.List;
6 import java.util.Map;
7 import android.app.ListActivity;
8 import android.os.Bundle;
9 import android.widget.SimpleAdapter;
10
11 public class Listview03Activity extends ListActivity {
12
13 private static String[] aa = new String[]{"hello world","this is my listview",
14 "邵洋江加油","你会成功的","you will success"};
15
16 private static int[] draw = new int[]{R.drawable.brick,R.drawable.calendar,R.drawable.eoemarket
17 ,R.drawable.ic_launcher,R.drawable.terminater,R.drawable.whitesociety};
18
19 @Override
20 public void onCreate(Bundle savedInstanceState)
21 {
22 super.onCreate(savedInstanceState);
23 //每个list里面放的都是MAP,map里面放的是键值对,这里指图片和文字
24 List<Map<String, Object>> Items = new ArrayList<Map<String, Object>>();
25 //把该显示的内容放到list中
26 for (int i = 0; i < aa.length; i++)
27 {
28 Map<String, Object> item = new HashMap<String, Object>();
29 item.put("image", draw[i]);
30 item.put("textview1", aa[i]);
31 Items.add(item);
32 }
33 //构建适配器Adapter,将数据与显示数据的布局页面绑定
34 SimpleAdapter simpleAdapter = new SimpleAdapter(this, Items,
35 R.layout.main, new String[]{ "textview1", "image" },
36 new int[]{ R.id.textview1, R.id.image});
37 //通过setAdapter()方法把适配器设置给ListView
38 setListAdapter(simpleAdapter);
39 }
40 }
如果还想单机每个listview的item出现响应,可以使用下面这个方法
View Code
1 listView.setOnItemClickListener(new OnItemClickListener() {
2
3 @Override
4 public void onItemClick(AdapterView<?> parent, View view,
5 int position, long id) {
6 //强制转换为ListView
7 ListView lv =(ListView)parent;
8 //得到item的位置
9 HashMap<String,Object> item = (HashMap<String,Object>)lv.getItemAtPosition(position);
10 //显示
11 Toast.makeText(MainActivity.this, item.get("listview1").toString(), 1).show();
12
13 }
14 });
效果图:
如果还想深入了解,下面的链接不错
Android之Adapter用法总结:http://kb.cnblogs.com/a/2328334/