ListView组件使用

    技术2022-05-20  38

    我是参考:http://www.cnblogs.com/zhangdongzi/archive/2011/04/15/2016982.html

     

    通常我们需要展示一些列表集合数据到手机屏幕时,通常采用ListView组件,该组件提供一些可以定制的列表展示功能,但是它需要数据 源,android通过数据适配器来沟通ListView与数据源。可以充当ListView数据设配器的adapter有很多,可定制性也更加广泛。通 常有如下几种:

    ArrayAdapter  SimpleAdapter CursorAdapter ,他们都来继承自BaseAdapter。

    结构

    继承关系

    public interface ListAdapter extends Adapter

     

    android.widget.ListAdapter

     

    子类及间接子类

    直接子类

             ArrayAdapter<T>, BaseAdapter, CursorAdapter, HeaderViewListAdapter, ResourceCursorAdapter, SimpleAdapter, SimpleCursorAdapter, WrapperListAdapter

    从上述可以知道,ListView需要的是继承自ListAdapter接口的类,也可以知道它的一些子类是我们需要讲到的,现在开始

    现在我们首先采用ArrayAdapter,ArrayAdapter<T> 它接受一个泛型对象。在这里我们可以使用String类型,用来表示文字吧。

    我们提供字符串数组作为数据源,当然也可以是List<String>

    private String [] list={"ArrayAdapter","ArrayAdapter","ArrayAdapter","ArrayAdapter"};

    我们查看ArrayAdapter构造函数的参数定义。

    public ArrayAdapter (Context context, int textViewResourceId, T[] objects)

    其中第一个参数:表示由那个上下文来控制,第二个参数:布局文件ID,第三个参数:泛型的集合对象或者数组。

    于是,我们可以采用这样的形式:

     ArrayAdapter<String> adapter=new ArrayAdapter<String>     (this, android.R.layout.simple_list_item_1, list);     listView.setAdapter(adapter);

      它显示的是一组字符串,每个项是按照系统默认的布局文件android.R.layout.simple_list_item_1。

     使用ArrayAdapter通常是用来表示字符串列表的,如果你想实现更为复杂的列表项,那么请看余下几节。

     

     

     

     

     

    上一节中一些列表集合数据到手机屏幕时,通常采用ListView组件+ArrayAdapter. 

    虽然它能为我们提供展示数据列表的能力,但是展示的项却不能定制,如果我们的项是由2个TextView组成的,它就无 能为力了。项目中大部分的不单单是展示简单的项模板,更多时候,我们可以对项模板进行一些定制,来满足我们的需求,假设项模板需要展示2个 TextView 呢?怎么办?

     我们可以使用SimpleAdapter+ListView来实现。

     SimpleAdapter其中一个构造函数如下:

    public SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)  第一个参数:当前上下文对象。第二个参数:一个List类型的泛型集合,泛型类型必须继承之Map类型。第三个:布局资源的ID,

     第四个参数:需要绑定的Key列表。第五个参数:与Key列表项对应的资源文件中的具体组件ID集合。

    有以上的理论基础,我们知道使用SimpleAdapter会带来这样的好处:

    1:可以自定义任何项模板,自由度很高(取决于美工水平)

    2:可以为项模板指定一个匹配的数据

     

     

     

    上一节中使用ListView+SimpleAdapter来展示列表数据,但是它只接受List<? extends Map<String, ?>> 类型数据,很多时候我们的数据是从SQLite数据库中来的,通常SQLite返回的是一个Cursor类型数据,要完全使用在 SimpleAdapter中,只能把Cursor数据取出再放在List<? extends Map<String, ?>>中,这样一来做了一些无用功,耗费了计算,那么有没有更好的办法直接把Cursor放在一个适配器中,用来为ListView展示数据 呢?

      很明显的,有了SimpleCursorAdapter类,这个类就可以为我们解决上述问题。

    查看SimpleCursorAdapter构造函数:

    public SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to)

     我们可以了解到它与SimpleAdapter的是多么相似, 只是提供的数据源方式不同。

    public SimpleAdapter (Context context, int layout, List<? extends Map<String, ?>> data, String[] from, int[] to)

    其实ArrayAdapter,SimpleCursorAdapter,SimpleAdapter这三种适配器只是接受的数据源不同而已。

    SimpleCursorAdapter 一般是接受数据库中cursor数据,那么现在我们就用SQLite数据库为它提供数据:


    最新回复(0)