android ListView详解

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

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

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

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

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

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

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

我们从最简单的ListView开始:


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并且定义一个布局文件(当然也可以使用系统自带的)。

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


<?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>

下面是实现代码:

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究竟是如何工作的。效果如下:

<?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>
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了。

运行效果如下图:

转载于:https://www.cnblogs.com/olvo/archive/2012/04/14/2447271.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/409922.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[html] iframe在更改了src之后,不出现后退或者前进按钮怎么解决?

[html] iframe在更改了src之后&#xff0c;不出现后退或者前进按钮怎么解决&#xff1f; 更改src时可以先删除旧的iframe后&#xff0c;新建一个iframe设置好src添加进去个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&#xff0c; 但坚持一定很酷。…

python一次性输入3个数_python实现输入数字的连续加减方法

不用库&#xff0c;写了很久&#xff0c;一直出bug&#xff0c;到网上一搜&#xff0c;可以直接输入之后&#xff0c;eval(str)即可得到结果&#xff01; eval程序如下&#xff1a; sinput("请输入要运算的数字") print("The result is{}".format(eval(s))…

gd动态曲线 php_php中用GD绘制折线图

1 ClassChart{2 private $image; //定义图像3 private $title; //定义标题4 private $ydata; //定义Y轴数据5 private $xdata; //定义X轴数据6 private $seriesName; //定义每个系列数据的名称7 private $color; //定义条形图颜色8 private $bgcolor; //定义图片背景颜色9 priv…

Nginx网站用户认证

一、Nginx网站用户认证 用户认证&#xff1a;用户访问网页时需要输入一个用户名和密码才能打开网页。 nginx的默认网页时安装目录下的html/index.html&#xff0c;配置文件在安装目录下的conf目录中的nginx.conf 无用户认证网页 修改配置文件/usr/local/nginx/conf/nginx.conf(…

STL源码剖析学习二:空间配置器(allocator)

STL源码剖析学习二&#xff1a;空间配置器&#xff08;allocator&#xff09; 标准接口&#xff1a;vlaue_typepointerconst_pointerreferenceconst_referencesize_typedifference_typerebindallocator()--default constructorallocator(const allocator<U>&--copy c…

[html] iframe如何自动调整高度?

[html] iframe如何自动调整高度&#xff1f; 未跨域时&#xff0c;在iframe中利用他的父窗口对象将本页面的滚动高度设置给iframe的height 跨域时&#xff0c;在iframe中将自己的的滚动高设置在本页面内的一个隐藏于父页面不跨域的iframe的hash值&#xff0c; 在隐藏的iframe中…

python selenium 处理弹窗_python+selenium 抓取弹出对话框信息

抓取弹出对话框信息&#xff0c;困挠了我很久&#xff0c;我百度了很久&#xff0c;一直没有找到我想要的内容。最近学习到了。 有两种方法&#xff1a; 1、driver.switch_to.alert.text 2、result EC.alert_is_present()(driver).text 这个要导入from selenium.webdriver.sup…

Nginx基于域名的虚拟主机

一、基于域名的虚拟主机 修改配置文件/usr/local/nginx/conf/nginx.conf 创建新的虚拟主机的根目录和默认网页index.html 重新加载nginx的配置文件 查看两个虚拟主机 因为这两个域名是随便写的&#xff0c;所以需要修改windows系统的hosts文件&#xff0c;让电脑能够解析www.a.…

【100题】第三十四 实现一个队列

一&#xff0c;题目&#xff1a; 生产者消费者线程演示 一个生产者线程将int类型的数入列&#xff0c;一个消费者线程将int类型的数出列 二&#xff0c;分析&#xff1a; 这一个&#xff0c;为操作系统上的一个经典例子&#xff0c;以下是july给出的解答 …

[html] 如何禁止web端的页面缩放?

[html] 如何禁止web端的页面缩放&#xff1f; <meta name"viewport" content"widthdevice-width, initial-scale1,user-scalable0">个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&#xff0c; 但坚持一定很酷。欢迎大家…

centos安装后两个启动项、_Windows安装Centos7双系统后Windows启动项消失

方法一&#xff1a;在Centos7下root登陆编辑 /boot/grub2/grub.cfgvim /boot/grub2/grub.cfg在第一行添加menuentry "Windows10" {insmod ntfsset root(hd0,)chainloader }其中(hd0, 1)的1代表你的windows10安装所在的盘修改完毕后保存并退出然后设置Windows10为默认…

如何给定两个gps坐标 算出航向角_机器人开发如何配置ROS中的TF变换关系?

当我们进行机器人开发时&#xff0c;常常需要面对TF坐标转换&#xff0c;本文以 Autolabor Pro1 与思岚激光雷达为例&#xff0c;介绍ROS TF的使用。Autolabor Pro1是什么&#xff1f;Autolabor Pro1是一款室内外通用机器人移动底盘。该平台上可集成激光雷达、摄像头、GPS等传感…

Tomcat架构与原理

Tomcat架构与原理 架构图 原理 ①、用户点击网页内容&#xff0c;请求被发送到本机端口8080&#xff0c;被在那里监听的Coyote HTTP/1.1 Connector获得。 ②、Connector把该请求交给它所在的Service的Engine来处理&#xff0c;并等待Engine的回应。 ③、Engine获得请求localhos…

[html] 微软雅黑是有版权的,在页面中使用font-family:Microsoft YaHei会不会有版权问题呢?

[html] 微软雅黑是有版权的&#xff0c;在页面中使用font-family:Microsoft YaHei会不会有版权问题呢&#xff1f; font-family: Microsoft YaHei的写法&#xff0c;个人、商用都不会有版权问题&#xff0c;可以放心使用&#xff01;但是如果是通过font-face引用微软雅黑的话&…

aodv路由协议分析

1 AODV 报文格式 AODV 有三种基本的协议报文类型&#xff1a;RREQ 报文、RREP 报文和RRER 报文。 1.1 RREQ 报文 a. 对RREQ 的处理 接收到RREQ 的结点做如下处理&#xff1a; &#xff08;1&#xff09;创建一个表项&#xff0c;先不分配有效序列号&#xff0c;用于记录反向路径…

rfid射频前端的主要组成部分有_第4章 RFID的射频前端(simple).ppt

(1)阅读器天线电路 * Microchip 公司的13.56 MHz应答器(无源射频卡)MCRF355和MCRF360芯片的天线电路 无源应答器的天线电路多采用并联谐振回路 * 并联谐振回路 在研究并联谐振回路时&#xff0c;采用恒流源(信号源内阻很大)分析比较方便。 并联谐振 谐振条件 - 实际中线圈的电…

c语言转换为python语言_python和c语言

广告关闭 腾讯云11.11云上盛惠 &#xff0c;精选热门产品助力上云&#xff0c;云服务器首年88元起&#xff0c;买的越多返的越多&#xff0c;最高返5000元&#xff01; c语言是编译型语言&#xff0c;经过编译后&#xff0c;生成机器码&#xff0c;然后再运行&#xff0c;执行速…

Tomcat安装与使用

Tomcat安装与使用 Tomcat是JAVA语言编写的&#xff0c;需要jdk环境。jdk从Oracle官网下载&#xff0c;不过要求登录后才能下载。 Tomcat的主配置文件&#xff1a;安装路径下的 conf/server.xml。 Tomcat默认监听8080端口。 下载&安装jdk #卸载或升级自带的java环境。 #查找…

COJ1196(Staginner 去爬山)

题目大意&#xff1a;给定一个n*m的只含0和1的矩阵&#xff0c;从矩阵的最后一行中的某个1出发&#xff0c;每步只能走到相邻的且是1的格子中&#xff0c;求能达到的最大高度&#xff08;最小行数&#xff09;。 这题直接DFS即可&#xff0c;复杂度为O(N*M)。 View Code 1 #in…

[html] 对一个元素设置浮动后,它的特征是什么?

[html] 对一个元素设置浮动后&#xff0c;它的特征是什么&#xff1f; 浮动元素脱离正常的文档流浮动元素后的内联元素&#xff0c;将围绕在浮动元素周围浮动元素会造成父元素的高度坍塌个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&#xff0c; 但…