android ListView详解

在android开发中ListView是比较常用的组件,它以列表的形式展示具体内容,并且能够根据数据的长度自适应显示。抽空把对ListView的使用做了整理,并写了个小例子,如下图。

 列表的显示需要三个元素:

1.ListVeiw 用来展示列表的View。

2.适配器 用来把数据映射到ListView上的中介。

3.数据    具体的将被映射的字符串,图片,或者基本组件。

根据列表的适配器类型,列表分为三种,ArrayAdapter,SimpleAdapter和SimpleCursorAdapter

其中以ArrayAdapter最为简单,只能展示一行字。SimpleAdapter有最好的扩充性,可以自定义出各种效果。SimpleCursorAdapter可以认为是SimpleAdapter对数据库的简单结合,可以方面的把数据库的内容以列表的形式展示出来。

 我们从最简单的ListView开始:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
  * @author allin
  *
  */
public  class  MyListView extends  Activity {
 
     private  ListView listView;
     //private List<String> data = new ArrayList<String>();
     @Override
     public  void  onCreate(Bundle savedInstanceState){
         super .onCreate(savedInstanceState);
         
         listView = new  ListView( this );
         listView.setAdapter( new  ArrayAdapter<String>( this , android.R.layout.simple_expandable_list_item_1,getData()));
         setContentView(listView);
     }
     
     
     
     private  List<String> getData(){
         
         List<String> data = new  ArrayList<String>();
         data.add( "测试数据1" );
         data.add( "测试数据2" );
         data.add( "测试数据3" );
         data.add( "测试数据4" );
         
         return  data;
     }
}

上面代码使用了ArrayAdapter(Context context, int textViewResourceId, List<T> objects)来装配数据,要装配这些数据就需要一个连接ListView视图对象和数组数据的适配器来两者的适配工作,ArrayAdapter的构造需要三个参数,依次为this,布局文件(注意这里的布局文件描述的是列表的每一行的布局,android.R.layout.simple_list_item_1是系统定义好的布局文件只显示一行文字,数据源(一个List集合)。同时用setAdapter()完成适配的最后工作。运行后的现实结构如下图:

SimpleCursorAdapter

  sdk的解释是这样的:An easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file. You can specify which columns you want, which views you want to display the columns, and the XML file that defines the appearance of these views。简单的说就是方便把从游标得到的数据进行列表显示,并可以把指定的列映射到对应的TextView中。

  下面的程序是从电话簿中把联系人显示到类表中。先在通讯录中添加一个联系人作为数据库的数据。然后获得一个指向数据库的Cursor并且定义一个布局文件(当然也可以使用系统自带的)。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
  * @author allin
  *
  */
public  class  MyListView2 extends  Activity {
 
     private  ListView listView;
     //private List<String> data = new ArrayList<String>();
     @Override
     public  void  onCreate(Bundle savedInstanceState){
         super .onCreate(savedInstanceState);
         
         listView = new  ListView( this );
         
         Cursor cursor = getContentResolver().query(People.CONTENT_URI, null , null , null , null );
         startManagingCursor(cursor);
         
         ListAdapter listAdapter = new  SimpleCursorAdapter( this , android.R.layout.simple_expandable_list_item_1,
                 cursor,
                 new  String[]{People.NAME},
                 new  int []{android.R.id.text1});
         
         listView.setAdapter(listAdapter);
         setContentView(listView);
     }
     
     
}

 Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);先获得一个指向系统通讯录数据库的Cursor对象获得数据来源。

 startManagingCursor(cursor);我们将获得的Cursor对象交由Activity管理,这样Cursor的生命周期和Activity便能够自动同步,省去自己手动管理Cursor。

 SimpleCursorAdapter 构造函数前面3个参数和ArrayAdapter是一样的,最后两个参数:一个包含数据库的列的String型数组,一个包含布局文件中对应组件id的int型数组。其作用是自动的将String型数组所表示的每一列数据映射到布局文件对应id的组件上。上面的代码,将NAME列的数据一次映射到布局文件的id为text1的组件上。

注意:需要在AndroidManifest.xml中如权限:<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>

运行后效果如下图:

SimpleAdapter

simpleAdapter的扩展性最好,可以定义各种各样的布局出来,可以放上ImageView(图片),还可以放上Button(按钮),CheckBox(复选框)等等。下面的代码都直接继承了ListActivity,ListActivity和普通的Activity没有太大的差别,不同就是对显示ListView做了许多优化,方面显示而已。

下面的程序是实现一个带有图片的类表。

首先需要定义好一个用来显示每一个列内容的xml

vlist.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<? xml  version = "1.0"  encoding = "utf-8" ?>
< LinearLayout  xmlns:android = "http://schemas.android.com/apk/res/android"
     android:orientation = "horizontal"  android:layout_width = "fill_parent"
     android:layout_height = "fill_parent" >
 
 
     < ImageView  android:id = "@+id/img"
         android:layout_width = "wrap_content"
         android:layout_height = "wrap_content"
         android:layout_margin = "5px" />
 
     < LinearLayout  android:orientation = "vertical"
         android:layout_width = "wrap_content"
         android:layout_height = "wrap_content" >
 
         < TextView  android:id = "@+id/title"
             android:layout_width = "wrap_content"
             android:layout_height = "wrap_content"
             android:textColor = "#FFFFFFFF"
             android:textSize = "22px"  />
         < TextView  android:id = "@+id/info"
             android:layout_width = "wrap_content"
             android:layout_height = "wrap_content"
             android:textColor = "#FFFFFFFF"
             android:textSize = "13px"  />
 
     </ LinearLayout >
 
 
</ LinearLayout >

下面是实现代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
  * @author allin
  *
  */
public  class  MyListView3 extends  ListActivity {
 
 
     // private List<String> data = new ArrayList<String>();
     @Override
     public  void  onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
 
         SimpleAdapter adapter = new  SimpleAdapter( this ,getData(),R.layout.vlist,
                 new  String[]{ "title" , "info" , "img" },
                 new  int []{R.id.title,R.id.info,R.id.img});
         setListAdapter(adapter);
     }
 
     private  List<Map<String, Object>> getData() {
         List<Map<String, Object>> list = new  ArrayList<Map<String, Object>>();
 
         Map<String, Object> map = new  HashMap<String, Object>();
         map.put( "title" , "G1" );
         map.put( "info" , "google 1" );
         map.put( "img" , R.drawable.i1);
         list.add(map);
 
         map = new  HashMap<String, Object>();
         map.put( "title" , "G2" );
         map.put( "info" , "google 2" );
         map.put( "img" , R.drawable.i2);
         list.add(map);
 
         map = new  HashMap<String, Object>();
         map.put( "title" , "G3" );
         map.put( "info" , "google 3" );
         map.put( "img" , R.drawable.i3);
         list.add(map);
         
         return  list;
     }
}

使用simpleAdapter的数据用一般都是HashMap构成的List,list的每一节对应ListView的每一行。HashMap的每个键值数据映射到布局文件中对应id的组件上。因为系统没有对应的布局文件可用,我们可以自己定义一个布局vlist.xml。下面做适配,new一个SimpleAdapter参数一次是:this,布局文件(vlist.xml),HashMap的 title 和 info,img。布局文件的组件id,title,info,img。布局文件的各组件分别映射到HashMap的各元素上,完成适配。

运行效果如下图:

有按钮的ListView

但是有时候,列表不光会用来做显示用,我们同样可以在在上面添加按钮。添加按钮首先要写一个有按钮的xml文件,然后自然会想到用上面的方法定义一个适配器,然后将数据映射到布局文件上。但是事实并非这样,因为按钮是无法映射的,即使你成功的用布局文件显示出了按钮也无法添加按钮的响应,这时就要研究一下ListView是如何现实的了,而且必须要重写一个类继承BaseAdapter。下面的示例将显示一个按钮和一个图片,两行字如果单击按钮将删除此按钮的所在行。并告诉你ListView究竟是如何工作的。效果如下:

vlist2.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<? xml  version = "1.0"  encoding = "utf-8" ?>
< LinearLayout  xmlns:android = "http://schemas.android.com/apk/res/android"
     android:orientation = "horizontal"
     android:layout_width = "fill_parent"
     android:layout_height = "fill_parent" >
 
 
     < ImageView  android:id = "@+id/img"
         android:layout_width = "wrap_content"
         android:layout_height = "wrap_content"
         android:layout_margin = "5px" />
 
     < LinearLayout  android:orientation = "vertical"
         android:layout_width = "wrap_content"
         android:layout_height = "wrap_content" >
 
         < TextView  android:id = "@+id/title"
             android:layout_width = "wrap_content"
             android:layout_height = "wrap_content"
             android:textColor = "#FFFFFFFF"
             android:textSize = "22px"  />
         < TextView  android:id = "@+id/info"
             android:layout_width = "wrap_content"
             android:layout_height = "wrap_content"
             android:textColor = "#FFFFFFFF"
             android:textSize = "13px"  />
 
     </ LinearLayout >
 
 
     < Button  android:id = "@+id/view_btn"
         android:layout_width = "wrap_content"
         android:layout_height = "wrap_content"
         android:text = "@string/s_view_btn"
         android:layout_gravity = "bottom|right"  />
</ LinearLayout >

程序代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/**
  * @author allin
  *
  */
public  class  MyListView4 extends  ListActivity {
 
 
     private  List<Map<String, Object>> mData;
     
     @Override
     public  void  onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         mData = getData();
         MyAdapter adapter = new  MyAdapter( this );
         setListAdapter(adapter);
     }
 
     private  List<Map<String, Object>> getData() {
         List<Map<String, Object>> list = new  ArrayList<Map<String, Object>>();
 
         Map<String, Object> map = new  HashMap<String, Object>();
         map.put( "title" , "G1" );
         map.put( "info" , "google 1" );
         map.put( "img" , R.drawable.i1);
         list.add(map);
 
         map = new  HashMap<String, Object>();
         map.put( "title" , "G2" );
         map.put( "info" , "google 2" );
         map.put( "img" , R.drawable.i2);
         list.add(map);
 
         map = new  HashMap<String, Object>();
         map.put( "title" , "G3" );
         map.put( "info" , "google 3" );
         map.put( "img" , R.drawable.i3);
         list.add(map);
         
         return  list;
     }
     
     // ListView 中某项被选中后的逻辑
     @Override
     protected  void  onListItemClick(ListView l, View v, int  position, long  id) {
         
         Log.v( "MyListView4-click" , (String)mData.get(position).get( "title" ));
     }
     
     /**
      * listview中点击按键弹出对话框
      */
     public  void  showInfo(){
         new  AlertDialog.Builder( this )
         .setTitle( "我的listview" )
         .setMessage( "介绍..." )
         .setPositiveButton( "确定" , new  DialogInterface.OnClickListener() {
             @Override
             public  void  onClick(DialogInterface dialog, int  which) {
             }
         })
         .show();
         
     }
     
     
     
     public  final  class  ViewHolder{
         public  ImageView img;
         public  TextView title;
         public  TextView info;
         public  Button viewBtn;
     }
     
     
     public  class  MyAdapter extends  BaseAdapter{
 
         private  LayoutInflater mInflater;
         
         
         public  MyAdapter(Context context){
             this .mInflater = LayoutInflater.from(context);
         }
         @Override
         public  int  getCount() {
             // TODO Auto-generated method stub
             return  mData.size();
         }
 
         @Override
         public  Object getItem( int  arg0) {
             // TODO Auto-generated method stub
             return  null ;
         }
 
         @Override
         public  long  getItemId( int  arg0) {
             // TODO Auto-generated method stub
             return  0 ;
         }
 
         @Override
         public  View getView( int  position, View convertView, ViewGroup parent) {
             
             ViewHolder holder = null ;
             if  (convertView == null ) {
                 
                 holder= new  ViewHolder(); 
                 
                 convertView = mInflater.inflate(R.layout.vlist2, null );
                 holder.img = (ImageView)convertView.findViewById(R.id.img);
                 holder.title = (TextView)convertView.findViewById(R.id.title);
                 holder.info = (TextView)convertView.findViewById(R.id.info);
                 holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);
                 convertView.setTag(holder);
                 
             } else  {
                 
                 holder = (ViewHolder)convertView.getTag();
             }
             
             
             holder.img.setBackgroundResource((Integer)mData.get(position).get( "img" ));
             holder.title.setText((String)mData.get(position).get( "title" ));
             holder.info.setText((String)mData.get(position).get( "info" ));
             
             holder.viewBtn.setOnClickListener( new  View.OnClickListener() {
                 
                 @Override
                 public  void  onClick(View v) {
                     showInfo();                
                 }
             });
             
             
             return  convertView;
         }
         
     }
     
     
     
     
}

  下面将对上述代码,做详细的解释,listView在开始绘制的时候,系统首先调用getCount()函数,根据他的返回值得到listView的长度(这也是为什么在开始的第一张图特别的标出列表长度),然后根据这个长度,调用getView()逐一绘制每一行。如果你的getCount()返回值是0的话,列表将不显示同样return 1,就只显示一行。

  系统显示列表时,首先实例化一个适配器(这里将实例化自定义的适配器)。当手动完成适配时,必须手动映射数据,这需要重写getView()方法。系统在绘制列表的每一行的时候将调用此方法。getView()有三个参数,position表示将显示的是第几行,covertView是从布局文件中inflate来的布局。我们用LayoutInflater的方法将定义好的vlist2.xml文件提取成View实例用来显示。然后将xml文件中的各个组件实例化(简单的findViewById()方法)。这样便可以将数据对应到各个组件上了。但是按钮为了响应点击事件,需要为它添加点击监听器,这样就能捕获点击事件。至此一个自定义的listView就完成了,现在让我们回过头从新审视这个过程。系统要绘制ListView了,他首先获得要绘制的这个列表的长度,然后开始绘制第一行,怎么绘制呢?调用getView()函数。在这个函数里面首先获得一个View(实际上是一个ViewGroup),然后再实例并设置各个组件,显示之。好了,绘制完这一行了。那 再绘制下一行,直到绘完为止。在实际的运行过程中会发现listView的每一行没有焦点了,这是因为Button抢夺了listView的焦点,只要布局文件中将Button设置为没有焦点就OK了。

运行效果如下图:

源码下载

分类:  android技术
标签:  androidListView
53
0
(请您对文章做出评价)
« 博主前一篇: 给Chrome穿上Android的衣服
» 博主后一篇: android service 学习(上)
posted @  2010-05-11 01:07  allin.android 阅读(220560) 评论( 76编辑  收藏
1 2

  
#27楼   2011-05-15 01:19 |  matako   
感谢啊!!内牛满面啊·············
  
#28楼   2011-05-23 13:50 |  hahajing9   
为了感谢lz我还特意申请了一个账号,很感谢啊!
  
#29楼   2011-05-24 13:48 |  amey   
楼主真是好人啊,强烈支持啊!!
  
#30楼   2011-05-27 17:09 |  semaru   
楼主,请问将Button换成ImageButton如何设置为没有焦点?
  
#31楼   2011-06-30 16:15 |  whysqwhw   
引用 hahajing9:为了感谢lz我还特意申请了一个账号,很感谢啊!

  
#32楼   2011-07-07 16:52 |  黑菜妞妞   
挺好哈~~~
  
#33楼   2011-07-14 13:28 |  yuanbin Song   
还用要源码么?我感觉者上面已经是源码了啊
  
#34楼   2011-07-19 17:14 |  perfect_yang   
代码还缺少一部分吧,求打包源码,不胜感激,perfect_yang@yeah.net
  
#35楼   2011-07-21 16:26 |  Virus-BeautyCode   
好文,顶你一下
  
#36楼   2011-07-27 11:53 |  LiLiNiuNiu   
楼主您好,我参考您的文章也写了一篇ListView的说明,在我的文章里边引用到了您的两张图片,如果您有意见请告诉我我马上删除,谢谢!
  
#37楼   2011-07-27 14:48 |  Tiger_Dog   
不错 很详细
  
#38楼 [ 楼主2011-07-31 19:38 |  allin.android   
@LiLiNiuNiu
没关系,注明来源就可以
  
#39楼   2011-08-03 12:02 |  王瑾   
  
#40楼   2011-08-05 10:11 |  ianan   
请问楼主,读联系人那个例子我想点击一下人名,通过Toast来显示他的名字,这个怎么实现呢
  
#41楼   2011-08-08 10:00 |  小标标   
谢谢楼主,留下;
  
#42楼   2011-08-14 01:47 |  SkyHacker   
博主你好,我有点问题想请教一下。
为什么要用List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();而不用ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

为什么用用Map<String, Object> map = new HashMap<String, Object>();不用HashMap<String, Object> map = new HashMap<String, Object>();
  
#43楼   2011-08-14 01:58 |  SkyHacker   
还有,字体大小应该用sp比较好吧,控件大小用dp。在网上看的~
  
#44楼   2011-08-14 15:37 |  狐狸喝粥   
最后一段listview的实现流程让小弟很受益,感谢!
  
#45楼   2011-08-28 12:25 |  香山早秋   
很是感谢
  
#46楼   2011-08-30 21:07 |  香山早秋   
你好,我在实际操作过程中遇到了一些问题,可以给个联系方式联系一下吗?非常感谢
  
#47楼   2011-09-02 10:28 |  上帝脚瓜   
楼主真的很感谢你这篇文章,让我解决了 ListView里面触发按钮的事件。。好文章啊~再次感谢。
  
#48楼   2011-09-07 15:51 |  逍遥无极   
好文,顶楼主,受益匪浅啊
  
#49楼   2011-09-26 23:04 |  YoyiorLee   
请教,listview 滚动的时候,图片是异步加载,但是会错位跳几下才回到正确的图片,是怎么会事?求解救
  
#50楼   2011-10-25 10:36 |  未出茅庐   
请问楼主,listview控件怎么没有在xml文件中定义?
  
#51楼   2011-10-27 13:49 |  李欢   
很好 感谢楼主!
  
#52楼   2011-11-14 22:56 |  kane1990   
为什么我写完运行发现三个图像最后显示的是一样的。其他的都正常。
我的getView()函数是这样写的。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public  View getView( int  position, View convertView, ViewGroup parent) {
     // TODO Auto-generated method stub
     
     if (convertView == null ){
         convertView = mInflater.inflate(R.layout.simpleadapter, null );
         ImageView imageView = (ImageView)convertView.findViewById(R.id.imageViewImg);
         TextView textViewTitle = (TextView)convertView.findViewById(R.id.textViewTitle);
         TextView textViewInfo = (TextView)convertView.findViewById(R.id.textViewInfo);
         Button buttonMore = (Button)convertView.findViewById(R.id.buttonMore);
         Integer imgId = (Integer)mdata.get(position).get( "img" );
         imageView.setBackgroundResource(imgId);
         Log.d( "kane" , "image id:"  + imgId);
         final  String title =  (String)mdata.get(position).get( "title" );
         final  String info = (String)mdata.get(position).get( "info" );
         textViewTitle.setText(title);
         textViewInfo.setText(info);
         buttonMore.setOnClickListener( new  View.OnClickListener() {
             
             @Override
             public  void  onClick(View v) {
                 // TODO Auto-generated method stub
                 show(title,info);
             }
         });
     }
     return  convertView;
}

运行结果如下(为什么三个图像是一样的,而且我log的三个id是不一样的啊。很困惑。。。)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本系统的研发具有重大的意义,在安全性方面,用户使用浏览器访问网站时,采用注册和密码等相关的保护措施,提高系统的可靠性,维护用户的个人信息和财产的安全。在方便性方面,促进了校园失物招领网站的信息化建设,极大的方便了相关的工作人员对校园失物招领网站信息进行管理。 本系统主要通过使用Java语言编码设计系统功能,MySQL数据库管理数据,AJAX技术设计简洁的、友好的网址页面,然后在IDEA开发平台中,编写相关的Java代码文件,接着通过连接语言完成与数据库的搭建工作,再通过平台提供的Tomcat插件完成信息的交互,最后在浏览器中打开系统网址便可使用本系统。本系统的使用角色可以被分为用户和管理员,用户具有注册、查看信息、留言信息等功能,管理员具有修改用户信息,发布寻物启事等功能。 管理员可以选择任一浏览器打开网址,输入信息无误后,以管理员的身份行使相关的管理权限。管理员可以通过选择失物招领管理,管理相关的失物招领信息记录,比如进行查看失物招领信息标题,修改失物招领信息来源等操作。管理员可以通过选择公告管理,管理相关的公告信息记录,比如进行查看公告详情,删除错误的公告信息,发布公告等操作。管理员可以通过选择公告类型管理,管理相关的公告类型信息,比如查看所有公告类型,删除无用公告类型,修改公告类型,添加公告类型等操作。寻物启事管理页面,此页面提供给管理员的功能有:新增寻物启事,修改寻物启事,删除寻物启事。物品类型管理页面,此页面提供给管理员的功能有:新增物品类型,修改物品类型,删除物品类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值