Android自定义适配器的编写
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
ListView :在Android应用开发过程中属于最常用的系统组件之一,当然可能同学们问为什么会突然游戏开发中讲这个,呵呵,其实在游戏开发中,也会常常使用到系统组件,比如游戏排行榜,简单的游戏关卡选择等等,都可以来使用ListView来实现;
当然关于ListView我想大家都会使用了,那么这篇文章也不是跟大家讲解ListView是如果使用的,而是如何自定义通用适配器类;
在ListView三种适配器当中,最受大家青睐的肯定就是SimpleAdapter 适配器,用过的童鞋们都很清楚,它的扩展性很强,可以将ListView中每一项都使用自定义布局,插入N多组件;但是SimpleAdapter也有弱点,那就是当ListView中每一项有Button、CheckBox等这些有事件的组件,我们想监听它们就必须自定义适配器!那么今天的重点也就是来讲解一下如何写一个自定义通用适配器类!
SimpleAdapter 构造的时候,我们知道需要五个参数来进行映射数据到ListView中,那么我们今天的自定义通用适配器其实也就是实现系统SimpleAdapter的一个自定义版;
OK,可能我说这么多,大家还是不太懂,其实今天要讲述的自定义通用适配器优点有两点:
1.使用通用适配器就不需要每次使用自定义适配器的时候,都要去重新去写一个,太累。。。。
2.构造方法与SimpleAdapter构造方法相同,五个参数也一摸一样!
3.只需要在自定义的适配器类中,将我们需要监听的组件进行设置监听即可!别的代码不需要去改动!
例如我们需要完成下图这种ListView:
(图1)
首先我们来完成ListView中每项的布局:main.xml:
xmlns:android="/apk/res/android " android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" > android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/iv" /> android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" > android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:id="@+id/bigtv" /> android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10sp" android:id="@+id/smalltv" />
复制代码
修改源码:MainActivity.java:
public class MainActivity extends Activity {
private SimpleAdapter adapter;// 声明适配器对象
private ListView listView; // 声明列表视图对象
private List
public static MainActivity ma;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ma = this;
// 实例化列表容器
list = new ArrayList
listView = new ListView(this);// 实例化列表视图
// 实例一个列表数据容器
Map
// 往列表容器中添加数据
map.put("item1_imageivew", R.drawable.icon);
map.put("item1_bigtv", "BIGTV");
map.put("item1_smalltv", "SMALLTV");
// 将列表数据添加到列表容器中
list.add(map);
// --使用系统适配器,无法实现组件监听;
// //实例适配器
adapter = new SimpleAdapter(this, list, yout.main, new String[] {