1.概念

Adapter是连接后端数据和前端显示的适配器接口,是数据和UI(View)之间一个重要的纽带。在常见的View(ListView,GridView)等地方都需要用到Adapter。如下图直观的表达了Data、Adapter、View三者的关系:

Android中所有的Adapter一览:

由图可以看到在Android中与Adapter有关的所有接口、类的完整层级图。在我们使用过程中可以根据自己的需求实现接口或者继承类进行一定的扩展。比较常用的有 BaseAdapter,SimpleAdapter,ArrayAdapter,SimpleCursorAdapter等。

  • BaseAdapter是一个抽象类,继承它需要实现较多的方法,所以也就具有较高的灵活性;
  • ArrayAdapter支持泛型操作,最为简单,只能展示一行字。
  • SimpleAdapter有最好的扩充性,可以自定义出各种效果。
  • SimpleCursorAdapter可以适用于简单的纯文字型ListView,它需要Cursor的字段和UI的id对应起来。如需要实现更复杂的UI也可以重写其他方法。可以认为是SimpleAdapter对数据库的简单结合,可以方便地把数据库的内容以列表的形式展示出来。

2.应用案例

1)ArrayAdapter

列表的显示需要三个元素:

a.ListVeiw 用来展示列表的View。

b.适配器 用来把数据映射到ListView上的中介。

c.数据    具体的将被映射的字符串,图片,或者基本组件。

案例一

public class ArrayAdapterActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//列表项的数据
String[] strs = {"1","2","3","4","5"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,strs);
setListAdapter(adapter);
}
}

案例二

    public class MyListView extends Activity {

        private ListView listView;
//private List<String> data = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState); listView = new ListView(this);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,getData()));
setContentView(listView);
} private List<String> getData(){ List<String> data = new ArrayList<String>();
data.add("测试数据1");
data.add("测试数据2");
data.add("测试数据3");
data.add("测试数据4"); return data;
}
}

上面代码使用了ArrayAdapter(Context context, int textViewResourceId, List<T> objects)来装配数据,要装配这些数据就需要一个连接ListView视图对象和数组数据的适配器来两者的适配工作,ArrayAdapter的构造需要三个参数,依次为this,布局文件(注意这里的布局文件描述的是列表的每一行的布局,android.R.layout.simple_list_item_1是系统定义好的布局文件只显示一行文字,数据源(一个List集合)。同时用setAdapter()完成适配的最后工作。效果图如下:

2)SimpleAdapter
  simpleAdapter的扩展性最好,可以定义各种各样的布局出来,可以放上ImageView(图片),还可以放上Button(按钮),CheckBox(复选框)等等。下面的代码都直接继承了ListActivity,ListActivity和普通的Activity没有太大的差别,不同就是对显示ListView做了许多优化,方面显示而已。

案例一

simple.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
/>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textSize="20sp"
/>
</LinearLayout>
public class SimpleAdapterActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); SimpleAdapter adapter = new SimpleAdapter(this, getData(), R.layout.simple, new String[] { "title", "img" }, new int[] { R.id.title, R.id.img });
setListAdapter(adapter);
} private List<Map<String, Object>> getData() {
//map.put(参数名字,参数值)
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", "摩托罗拉");
map.put("img", R.drawable.icon);
list.add(map); map = new HashMap<String, Object>();
map.put("title", "诺基亚");
map.put("img", R.drawable.icon);
list.add(map); map = new HashMap<String, Object>();
map.put("title", "三星");
map.put("img", R.drawable.icon);
list.add(map);
return list;
} }

案例二
  下面的程序是实现一个带有图片的类表。首先需要定义好一个用来显示每一个列内容的xml,vlist.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5px"/>
<LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="#FFFFFFFF" android:textSize="22px" />
<TextView android:id="@+id/info" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="#FFFFFFFF" android:textSize="13px" />
</LinearLayout>
</LinearLayout>
public class MyListView3 extends ListActivity {
// private List<String> data = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); SimpleAdapter adapter = new SimpleAdapter(this,getData(),R.layout.vlist,
new String[]{"title","info","img"},
new int[]{R.id.title,R.id.info,R.id.img});
setListAdapter(adapter);
} private List<Map<String, Object>> getData() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>();
map.put("title", "G1");
map.put("info", "google 1");
map.put("img", R.drawable.i1);
list.add(map); map = new HashMap<String, Object>();
map.put("title", "G2");
map.put("info", "google 2");
map.put("img", R.drawable.i2);
list.add(map); map = new HashMap<String, Object>();
map.put("title", "G3");
map.put("info", "google 3");
map.put("img", R.drawable.i3);
list.add(map); return list;
}
}

  使用simpleAdapter的数据用一般都是HashMap构成的List,list的每一节对应ListView的每一行。HashMap的每个键值数据映射到布局文件中对应id的组件上。因为系统没有对应的布局文件可用,我们可以自己定义一个布局vlist.xml。下面做适配,new一个SimpleAdapter参数一次是:this,布局文件(vlist.xml),HashMap的 title 和 info,img。布局文件的组件id,title,info,img。布局文件的各组件分别映射到HashMap的各元素上,完成适配。

运行效果如下图:

3)SimpleCursorAdapter

public class SimpleCursorAdapterActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//获得一个指向系统通讯录数据库的Cursor对象获得数据来源
Cursor cur = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
startManagingCursor(cur);
//实例化列表适配器 ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cur, new String[] {People.NAME}, new int[] {android.R.id.text1});
setListAdapter(adapter);
}
}

一定要以数据库作为数据源的时候,才能使用SimpleCursorAdapter,这里特别需要注意的一点是:不要忘了在AndroidManifest.xml文件中加入权限

<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>

效果如下:

4)BaseAdapter

  有时候,列表不光会用来做显示用,我们同样可以在在上面添加按钮。添加按钮首先要写一个有按钮的xml文件,然后自然会想到用上面的方法定义一个适配器,然后将数据映射到布局文件上。但是事实并非这样,因为按钮是无法映射的,即使你成功的用布局文件显示出了按钮也无法添加按钮的响应,这时就要研究一下ListView是如何现实的了,而且必须要重写一个类继承BaseAdapter。下面的示例将显示一个按钮和一个图片,两行字如果单击按钮将删除此按钮的所在行。并告诉你ListView究竟是如何工作的。

vlist2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5px"/>
<LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="#FFFFFFFF" android:textSize="22px" />
<TextView android:id="@+id/info" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="#FFFFFFFF" android:textSize="13px" />
</LinearLayout> <Button android:id="@+id/view_btn" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="@string/s_view_btn" android:layout_gravity="bottom|right" />
</LinearLayout>
/**
002 * @author
003 *
004 */
005 public class MyListView4 extends ListActivity {
006
007
008 private List<Map<String, Object>> mData;
009
010 @Override
011 public void onCreate(Bundle savedInstanceState) {
012 super.onCreate(savedInstanceState);
013 mData = getData();
014 MyAdapter adapter = new MyAdapter(this);
015 setListAdapter(adapter);
016 }
017
018 private List<Map<String, Object>> getData() {
019 List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
020
021 Map<String, Object> map = new HashMap<String, Object>();
022 map.put("title", "G1");
023 map.put("info", "google 1");
024 map.put("img", R.drawable.i1);
025 list.add(map);
026
027 map = new HashMap<String, Object>();
028 map.put("title", "G2");
029 map.put("info", "google 2");
030 map.put("img", R.drawable.i2);
031 list.add(map);
032
033 map = new HashMap<String, Object>();
034 map.put("title", "G3");
035 map.put("info", "google 3");
036 map.put("img", R.drawable.i3);
037 list.add(map);
038
039 return list;
040 }
041
042 // ListView 中某项被选中后的逻辑
043 @Override
044 protected void onListItemClick(ListView l, View v, int position, long id) {
045
046 Log.v("MyListView4-click", (String)mData.get(position).get("title"));
047 }
048
049 /**
050 * listview中点击按键弹出对话框
051 */
052 public void showInfo(){
053 new AlertDialog.Builder(this)
054 .setTitle("我的listview")
055 .setMessage("介绍...")
056 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
057 @Override
058 public void onClick(DialogInterface dialog, int which) {
059 }
060 })
061 .show();
062
063 }
064
065
066
067 public final class ViewHolder{
068 public ImageView img;
069 public TextView title;
070 public TextView info;
071 public Button viewBtn;
072 }
073
074
075 public class MyAdapter extends BaseAdapter{
076
077 private LayoutInflater mInflater;
078
079
080 public MyAdapter(Context context){
081 this.mInflater = LayoutInflater.from(context);
082 }
083 @Override
084 public int getCount() {
085 // TODO Auto-generated method stub
086 return mData.size();
087 }
088
089 @Override
090 public Object getItem(int arg0) {
091 // TODO Auto-generated method stub
092 return null;
093 }
094
095 @Override
096 public long getItemId(int arg0) {
097 // TODO Auto-generated method stub
098 return 0;
099 }
100
101 @Override
102 public View getView(int position, View convertView, ViewGroup parent) {
103
104 ViewHolder holder = null;
105 if (convertView == null) {
106
107 holder=new ViewHolder();
108
109 convertView = mInflater.inflate(R.layout.vlist2, null);
110 holder.img = (ImageView)convertView.findViewById(R.id.img);
111 holder.title = (TextView)convertView.findViewById(R.id.title);
112 holder.info = (TextView)convertView.findViewById(R.id.info);
113 holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);
114 convertView.setTag(holder);
115
116 }else {
117
118 holder = (ViewHolder)convertView.getTag();
119 }
120
121
122 holder.img.setBackgroundResource((Integer)mData.get(position).get("img"));
123 holder.title.setText((String)mData.get(position).get("title"));
124 holder.info.setText((String)mData.get(position).get("info"));
125
126 holder.viewBtn.setOnClickListener(new View.OnClickListener() {
127
128 @Override
129 public void onClick(View v) {
130 showInfo();
131 }
132 });
133
134
135 return convertView;
136 }
137
138 }
139 }

  下面将对上述代码,做详细的解释,listView在开始绘制的时候,系统首先调用getCount()函数,根据他的返回值得到listView的长度(这也是为什么在开始的第一张图特别的标出列表长度),然后根据这个长度,调用getView()逐一绘制每一行。如果你的getCount()返回值是0的话,列表将不显示同样return 1,就只显示一行。

  系统显示列表时,首先实例化一个适配器(这里将实例化自定义的适配器)。当手动完成适配时,必须手动映射数据,这需要重写getView()方法。系统在绘制列表的每一行的时候将调用此方法。getView()有三个参数,position表示将显示的是第几行,covertView是从布局文件中inflate来的布局。我们用LayoutInflater的方法将定义好的vlist2.xml文件提取成View实例用来显示。然后将xml文件中的各个组件实例化(简单的findViewById()方法)。这样便可以将数据对应到各个组件上了。但是按钮为了响应点击事件,需要为它添加点击监听器,这样就能捕获点击事件。至此一个自定义的listView就完成了,现在让我们回过头从新审视这个过程。系统要绘制ListView了,他首先获得要绘制的这个列表的长度,然后开始绘制第一行,怎么绘制呢?调用getView()函数。在这个函数里面首先获得一个View(实际上是一个ViewGroup),然后再实例并设置各个组件,显示之。好了,绘制完这一行了。那再绘制下一行,直到绘完为止。在实际的运行过程中会发现listView的每一行没有焦点了,这是因为Button抢夺了listView的焦点,只要布局文件中将Button设置为没有焦点就OK了。

效果如下:

adapter(转自Devin Zhang)的更多相关文章

  1. 初探ListView和Adapter

    关于Android Adapter(适配器),参考Devin Zhang’s blog.简单的说,Adapter起到的作用是使得前端的显示和后端的数据能够适配,用以下代码作为例子 1234567891 ...

  2. 收藏的技术文章链接(ubuntu,python,android等)

    我的收藏 他山之石,可以攻玉 转载请注明出处:https://ahangchen.gitbooks.io/windy-afternoon/content/ 开发过程中收藏在Chrome书签栏里的技术文 ...

  3. 国内及Github优秀开发人员列表

    自从入了Android软件开发的行道,解决问题和学习过程中免不了会参考别人的思路,浏览博文和门户网站成了最大的入口.下面这些列表取名为:国内及Github优秀开发人员列表,就是浏览后的成果. 虽然下述 ...

  4. atitit.设计模式(2) -----查表模式/ command 总结

    atitit.设计模式(2) -----查表模式/ command 总结 1. 应用场景: 1 1. 取代一瓦if else 1 2. 建设api rpc风格的时候儿. 1 3. 菜单是Command ...

  5. java synchronized关键字浅探

    synchronized 是 java 多线程编程中用于使线程之间的操作串行化的关键字.这种措施类似于数据库中使用排他锁实现并发控制,但是有所不同的是,数据库中是对数据对象加锁,而 java 则是对将 ...

  6. atitit.设计模式(2) -----查询方式/ command 总结

    atitit.设计模式(2) -----查询方式/ command 总结 1. 应用场景: 1 1. 代替一瓦if else 1 2. 建设api rpc风格的时候儿. 1 3. 菜单是Command ...

  7. 【Mood-14】龙虎榜 活跃在github中的1000位中国开发者

    Last cache created on 2015-01-07 by Github API v3. ♥ made by hzlzh just for fun. Rank Gravatar usern ...

  8. (七)Spring Cloud 配置中心config

      spring cloud config是一个基于http协议的远程配置实现方式. 通过统一的配置管理服务器进行配置管理,客户端通过http协议主动的拉取服务的的配置信息,完成配置获取. 下面我们对 ...

  9. 设计模式(七): 通过转接头来观察"适配器模式"(Adapter Pattern)

    在前面一篇博客中介绍了“命令模式”(Command Pattern),今天博客的主题是“适配器模式”(Adapter Pattern).适配器模式用处还是比较多的,如果你对“适配器模式”理解呢,那么自 ...

随机推荐

  1. iOS开发小技巧--获取自定义的BarButtonItem中的自定义View的方法(customView)

    如果BarButtonItem是通过[[UIBarButtonItem alloc] initWithCustomView:(nonnull UIView *)]方法设置的.某些情况下需要修改BarB ...

  2. Spring 配置文件中将common.properties文件外置

    将配置文件的路径从项目中移出来 1. 在springApplicationContext中 <context:property-placeholder location="file:$ ...

  3. 【URAL 1297】Palindrome 最长回文子串

    模板题,,,模板打错查了1h+QAQ #include<cmath> #include<cstdio> #include<cstring> #include< ...

  4. 【转】c# 调用windows API(user32.dll)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.R ...

  5. DEDE列表页直接获取下载链接

    我们得去设置软件频道的东西,先点击“核心”->"内容管理模型"中的软件模型进行编辑,将softlinks加入列表字段. 然后进入“系统”->"软件频道设置&q ...

  6. js-处理回车事件

    /**回车 */ function enterkey() { //兼容IE或其它其它浏览器 var event = arguments[0] || window.event; //兼容IE或其它浏览器 ...

  7. Python之几种重要的基本类型:元组,列表,字典,字符串,集合

    写在前面:重点讲解元组,列表,字典相关概念和常用操作. 一.元组(tuple) 1.特性:不可更改的数据序列.[理解:一旦创建元组,则这个元组就不能被修改,即不能对元组进行更新.增加.删除操作] 2. ...

  8. 【PowerOJ1740】 圆桌问题

    https://www.oj.swust.edu.cn/problem/show/1740 (题目链接) 题意 n个单位的人去吃饭,m张餐桌,同一单位的人不能在同一餐桌,问可行方案. Solution ...

  9. Jenkins使用FTP进行一键部署及回滚(Windows)

    前提条件: 1.必须有两台服务器,一个是生产环境,另一个是测试环境. 2.两台服务器上都必须安装了Jenkins. 3.其中,生产环境上的Jenkins已经开通的CLI的权限(Windows参考:ht ...

  10. 使用Chrome或Fiddler抓取WebSocket包

    首先,HTTP是建立在TCP协议基础上的,而WebSocket通常也是建立在TCP上,所以说为什么有些网页游戏抓不到包而有些又可以,这仅是因为你使用的抓包工具是针对了HTTP的通信协议. 我先从抽象的 ...