慕客网-Android必学-BaseAdapter的使用与优化-学习笔记
什么是数据适配器
数据适配器是数据源与视图(View)之间的桥梁,建立了两者之间的适配关系。数据的来源是各种各样的,但View能显示的格式却是有一定要求的,数据适配器是把各种各样的数据源转化成为View能显示的数据格式。
优点:
将数据的来源与数据的显示进行了解耦,降低程序的耦合性,提高可扩展性。
BaseAdapter是Android各种各样适配器里最通用的适配器。
BaseAdapter基本结构
- public int getCount() :适配器中 数据集中 数据的个数,即ListView需要显示的数据个数
- public Object getItem(int position) : 获取数据集中与指定索引对应的数据项
- public long getItemId(int position) : 获取指定行对应的ID
- public View getView(int position, View convertView, ViewGroup parent) :获取每一个Item的显示内容
在使用BaseAdapter时,我们需要自己创建一个类继承BaseAdapter,然后Eclipse会提醒我们实现上述四个方法,当给ListView设置了我们自己写的Adapter后,ListView内部会调用上述四个方法。
BaseAdapter的逗比式
这是BaseAdapter使用的基本形式,下面是实现步骤:
- 新建Android工程 MyBaseAdapter,准备界面布局
修改activity_main,将TextView改为ListView,如下:
<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="com.mybaseadapter.MainActivity" >
<ListView
android:id="@+id/lv_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
创建单条数据项的Layout布局:item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"