获取源代码 git clone https://github.com/coderebot/ListViewAutoAdapter.git 或者使用svn co https://github.com/coderebot/ListViewAutoAdapter
网上有很多介绍ListView的用法,大多涉及了Adapter。Android提供的Adapter主要有ArrayAdapter, SimpleAdapter, SimpleCursorAdapter。当然,也介绍了如何自己从BaseAdapter继承的方法。
但是,这些文章介绍的方法距离实际使用还是很有距离的,基本处于练手的级别。对于很多开发者来说,实现一个功能复杂、效率高的ListView还是有一点难度。
我根据自己的编程经验,结合网上的介绍,利用java的反射原理,提供一种使用更加简便、效率更高、控制更加灵活的方法。
我的灵感来源自SimpleAdapter。使用过SimpleAdapter的朋友都知道,SimpleAdapter是一种使用简单而功能强大的Adapter,可以实现大多数我们已知的ListView类型。但是SimpleAdapter还是存在很多问题:
- 它使用Map对象保存一条数据,空间和时间效率都不高;
- SimpleAdapter使用的数据和原始数据是不能直接共享,必须生成一个新的List<Map>对象
- View和数据的映射是固定的,不能根据我们的需要做调整,比如,如果数据是一个星期类型,就不能直接提供给View来显示。
我通过实现一个AutoBinderAdapter来解决以上遇到的问题。
为了便于说明,请先看截图:
代码下载可以到:http://download.csdn.net/detail/doon/6819483
Activity的布局很简单,就是一个listview: (activity_main.xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
listitem的布局也非常简单:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="fill_parent"