ListView解析二

来源:互联网 发布:java的可移植性 编辑:程序博客网 时间:2024/05/14 02:00

有了上一篇的基础,基本上可以做出一些个简单列表了,虽然它还只是样子货。但是,你肯定还会有些疑问,再看看这句:

ListView is aViewGroup that creates a list of scrollable items. The list items are automatically inserted to the list using aListAdapter。

列表视图是一个包含了一系列可滚动项的视图组。列表项通过列表适配器自动插入到列表中。疑问来了,什么是列表适配器?

一、什么是ListAdapter?

Extended Adapter that is the bridge between aListView and the data that backs the list. Frequently that data comes from a Cursor, but that is not required. The ListView can display any data provided that it is wrapped in a ListAdapter.

ListAdapter继承于Adapter,它是ListView和其数据之间的桥梁。一般,数据来自Cursor,但不是必须的。listview可以显示任何由适配器提供的数据。

也就是说,要让一个listview显示出来需要三个条件:

1. ListView (需要被显示的列表)。

2. Data, 与ListView绑定的数据,一般是一个Cursor或者一个字符串数组。

3. ListAdapter,是data和ListView的桥梁,起一个适配器的作用。

二、Adapter的体系结构

参考:http://lfcaolibin.iteye.com/blog/624204

这篇文章说的比较抽象,主要内容如下:

adapter的作用就是将要在列表内显示的数据和列表本身结合起来。列表本身只完成显示的作用,其实他就是继承自VIEWGROUP 类。但是他又有一个独特的函数就是setAdapter()就是完成了view和adapter的结合。adapter如同其本身含义,其实就是一个适配器,他可以对要显示的数据进行统一的封装,主要是将数据变成view提供给list。

我们先来看看adapter的体系:

public interface Adapter----0层(表示继承体系中的层次)
public interface ExpandableListAdapter---(无所谓层次因为没有其他接口继承实现它) 这是adapter的始祖,其他个性化的adapter均实现它并加入自己的接口。

 
public interface ListAdapter----1层
public interface SpinnerAdapter----1层
public interface WrapperListAdapter----2层(实现ListAdapter)

以上接口层面上的体系已经完了。可以看出来作为widgetview的桥梁adapter其实只分为2种:ListAdapter和 SpinnerAdapter以及ExpandableListAdapter。也就是说所有widget也就是基于list和spinne与 ExpandableList三种view形式的。

 

由于在实际使用时,我们需要将数据加入到Adapter,而以接口形式呈现的adapter无法保存数据,于是Adapter就转型为类的模式。
public abstract class BaseAdapter----2层(实现了ListAdapter和SpinnerAdapter) 以抽象类的形式出现构造了类型态下的顶层抽象,包容了List和Spinner
public class ArrayAdapter----3层
public class SimpleAdapter---3层
public class CursorAdapter----3层(CursorAdapter其后还有子类这里先不探讨)

 

基本体系有了之后,让我们看看顶层Adapter里有哪些方法(只列举常用的):
abstract Object getItem_r(int position)
abstract int getCount_r()
abstract long getItemId_r(int position)
abstract int getItemViewType_r(int position)
abstract View getView_r(int position,View convertVeiw,ViewGroup parent)


以上是比较重要的方法,ArrayAdapter他们也是重新实现以上方法的。在实际的开发过程中,往往我们要自己做属于自己的Adapter,以上方法都是需要重新实现的。这个在android提供的APIdemo例子中可以看到。

这里提到了很多没见过的东西,还好也有一些见过的,下回再细说。