文档详情

Android自定义适配器的编写.docx

发布:2024-04-24约9.16千字共15页下载文档
文本预览下载声明

ListView:在Android应用开发过程中属于最常用的系统组件之一,当然可能同学们问为什么会突然游戏开发中讲这个,呵呵,其实在游戏开发中,也会常常使用到系统组件,比如游戏排行榜,简单的游戏关卡选择等等,都可以来使用

ListView来实现;

当然关于ListView我想大家都会使用了,那么这篇文章也不是跟大家讲解

ListView是如果使用的,而是如何自定义通用适配器类;

在ListView三种适配器当中,最受大家青睐的肯定就是SimpleAdapter适配器,用过的童鞋们都很清楚,它的扩展性很强,可以将ListView中每一项都使用自定义布局,插入N多组件;但是SimpleAdapter也有弱点,那就是当ListView中每一项有Button、CheckBox等这些有事件的组件,我们想监听它们就必须自定义适配器!那么今天的重点也就是来讲解一下如何写一个自定义通用适配器类!

SimpleAdapter构造的时候,我们知道需要五个参数来进行映射数据到ListView中,那么我们今天的自定义通用适配器其实也就是实现系统SimpleAdapter的一个自定义版;

OK,可能我说这么多,大家还是不太懂,其实今天要讲述的自定义通用适配器优点有两点:

使用通用适配器就不需要每次使用自定义适配器的时候,都要去重新去写一个,太累。。。。

构造方法与SimpleAdapter构造方法相同,五个参数也一摸一样!

只需要在自定义的适配器类中,将我们需要监听的组件进行设置监听即可!别的代码不需要去改动!

例如我们需要完成下图这种ListView:

(图1)

首先我们来完成ListView中每项的布局:main.xml:

?xmlversion=1.0encoding=utf-8?

LinearLayoutxmlns:android=/apk/res/android

android:orientation=horizontalandroid:layout_width=fill_parentandroid:layout_height=fill_parent

ImageViewandroid:layout_width=wrap_contentandroid:layout_height=wrap_contentandroid:id=@+id/iv

/

LinearLayoutandroid:orientation=verticalandroid:layout_width=wrap_contentandroid:layout_height=wrap_content

TextView

android:layout_width=wrap_contentandroid:layout_height=wrap_contentandroid:textSize=20sp

android:id=@+id/bigtv

/

TextView

android:layout_width=wrap_contentandroid:layout_height=wrap_contentandroid:textSize=10spandroid:id=@+id/smalltv

/

/LinearLayout

Button

android:layout_width=wrap_contentandroid:layout_height=wrap_contentandroid:text=buttonandroid:id=@+id/btn

/

CheckBoxandroid:layout_width=wrap_contentandroid:layout_height=wrap_contentandroid:id=@+id/cb

/

/LinearLayout

复制代码

修改源码:MainActivity.java :

publicclassMainActivityextendsActivity{

privateSimpleAdapteradapter;//声明适配器对象

privateListViewlistView;//声明列表视图对象

privateListMapString,Objectlist;//声明列表容器

publicstaticMainActivityma;@Override

publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);

ma=this;

//实例化列表容器

list=newArrayList

显示全部
相似文档