`
qq986945193
  • 浏览: 79825 次
  • 性别: Icon_minigender_2
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

Android开发之 。。各种Adapter的用法

 
阅读更多

同样是一个ListView,可以用不同的Adapter让它显示出来,比如说最常用的ArrayAdapter,SimpleAdapter,SimpleCursorAdapter,以及重写BaseAdapter等方法。

  ArrayAdapter比较简单,但它只能用于显示文字。而SimpleAdapter则有很强的扩展性,可以自定义出各种效果,SimpleCursorAdapter则可以从数据库中读取数据显示在列表上,通过从写BaseAdapter可以在列表上加处理的事件等。


下面先来看看ArrayAdapter:

  1. packagecom.shang.test;
  2. importjava.util.ArrayList;
  3. importandroid.app.Activity;
  4. importandroid.os.Bundle;
  5. importandroid.widget.ArrayAdapter;
  6. importandroid.widget.ListView;
  7. /**
  8. *
  9. *@authorshangzhenxiang
  10. *
  11. */
  12. publicclassTestArrayAdapterActivityextendsActivity{
  13. privateListViewmListView;
  14. privateArrayList<String>mArrayList=newArrayList<String>();
  15. @Override
  16. protectedvoidonCreate(BundlesavedInstanceState){
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.testarrayadapter);
  19. mListView=(ListView)findViewById(R.id.myArrayList);
  20. mListView.setAdapter(newArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,getData()));
  21. }
  22. privateArrayList<String>getData(){
  23. mArrayList.add("测试数据1");
  24. mArrayList.add("测试数据2");
  25. mArrayList.add("测试数据3");
  26. mArrayList.add("测试数据4");
  27. mArrayList.add("测试数据5");
  28. mArrayList.add("测试数据6");
  29. returnmArrayList;
  30. }
  31. }

布局里面有个ListView就可以了:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="match_parent"
  5. android:layout_height="fill_parent">
  6. <TextView
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:text="@string/hello"/>
  10. <ListView
  11. android:id="@+id/myArrayList"
  12. android:layout_width="match_parent"
  13. android:layout_height="wrap_content"/>
  14. </LinearLayout>

上面的代码中用到了ArrayAdapter的构造方法:

public ArrayAdapter(Context context, int textViewResourceId, T[] objects)

API中是这样描述的:



  

其中Context为当前的环境变量,可以显示一行文字的一个布局文件,和一个List的集合,也就是数据源。

布局文件可以自己写,也可以用系统的,我这里是用的系统的。自己写的布局中包含一个TextView就可以了,当然系统中也有包含一个TextView的布局文件:就是android.R.layout.simple_expandable_list_item_1,调用这个比较方便。

这里给出运行后的效果图:


下面说说SimpleCursorAdapter:

  Api中是这么说的:An easy adapter to map columns from a cursorto TextViews or ImageViews defined in an XML file. You can specify whichcolumns you want, which views you want to display the columns, and the XML filethat defines the appearance of these views.

  简单的说就是 方便把Cursor中得到的数据进行列表显示,并可以把指定的列映射到指定的TextView上。

  我这里写的是从联系人中拿到数据并显示在列表上。代码如下

  1. packagecom.shang.test;
  2. importandroid.app.Activity;
  3. importandroid.database.Cursor;
  4. importandroid.os.Bundle;
  5. importandroid.provider.Contacts.People;
  6. importandroid.widget.ListView;
  7. importandroid.widget.SimpleCursorAdapter;
  8. /**
  9. *
  10. *@authorshangzhenxiang
  11. *
  12. */
  13. publicclassTestSimpleCursorAdapterextendsActivity{
  14. privateListViewmListView;
  15. privateCursormCursor;
  16. privateSimpleCursorAdaptermAdapter;
  17. @Override
  18. protectedvoidonCreate(BundlesavedInstanceState){
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.testsimplecursoradapter);
  21. mListView=(ListView)findViewById(R.id.mySimpleCursorList);
  22. mCursor=getContentResolver().query(People.CONTENT_URI,null,null,null,null);
  23. startManagingCursor(mCursor);
  24. mAdapter=newSimpleCursorAdapter(TestSimpleCursorAdapter.this,android.R.layout.simple_expandable_list_item_1,mCursor,newString[]{People.NAME},newint[]{android.R.id.text1});
  25. mListView.setAdapter(mAdapter);
  26. }
  27. }

mCursor =getContentResolver().query(People.CONTENT_URI, null, null, null, null);是先获得一个指向系统联系人的Cursor

startManagingCursor(mCursor);是指我们把Cursor交给这个Activity保管,这样Cursor便会和Activity同步,我们不用手动管理了。

simpleCursorAdapter API中是这样说的:


其中前面的2个参数跟ArrayAdapter中是一样的,第三个参数是传个来的参数, 其实也是数据源,后面的2个参数是2个数组,前一个是String【】类型的,而后一个是int【】类型的,说明前一个参数中的值对应的是从数据库中的字段,后一个是布局文件中和这个字段对应的id,也就是说这个字段对应得值要显示在哪里(比如说我们这里查到的联系人中的NAME字段,要显示在一个对应的TextView上面)。

这里我们具体看一下系统的布局,也就是我们这里的第二个参数的布局,便于理解,android.R.layout.simple_expandable_list_item_1.xml文件中是这么写的:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <!--Copyright(C)2006TheAndroidOpenSourceProject
  3. LicensedundertheApacheLicense,Version2.0(the"License");
  4. youmaynotusethisfileexceptincompliancewiththeLicense.
  5. YoumayobtainacopyoftheLicenseat
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  8. distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  9. WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  10. SeetheLicenseforthespecificlanguagegoverningpermissionsand
  11. limitationsundertheLicense.
  12. -->
  13. <TextViewxmlns:android="http://schemas.android.com/apk/res/android"
  14. android:id="@android:id/text1"
  15. android:layout_width="match_parent"
  16. android:layout_height="?android:attr/listPreferredItemHeight"
  17. android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
  18. android:textAppearance="?android:attr/textAppearanceLarge"
  19. android:gravity="center_vertical"
  20. />


注意他有一个id,这个id也是系统的id,这个布局中只有一个TextView,所以只能显示一个字段,我们这里显示的联系人的名字,

而最后的一个参数就是由这么写id组成的一个数据(如果有很多TextView的话)。比如说我们要显示很多字段,布局文件中就要写很多TextView,而每一个TextView都有一个ID,第三个参数中有多少个字段,第四个参数中就有多少个id,并一一对应。

我们来看一下运行效果图:

上面说到的2种方法都是显示的文字,比方说我们要显示图片怎么办呢,还要显示很多内容,还要按自己喜欢的布局排列怎么办呢,用SimpleAdapter,扩展性好,可以定义各种各样的布局。

代码如下:

  1. packagecom.shang.test;
  2. importjava.util.ArrayList;
  3. importjava.util.HashMap;
  4. importjava.util.List;
  5. importandroid.app.Activity;
  6. importandroid.os.Bundle;
  7. importandroid.widget.ListView;
  8. importandroid.widget.SimpleAdapter;
  9. /**
  10. *
  11. *@authorshangzhenxiang
  12. *
  13. */
  14. publicclassTestSimpleAdapterextendsActivity{
  15. privateListViewmListView;
  16. privateSimpleAdaptermAdapter;
  17. privateList<HashMap<String,Object>>mHashMaps;
  18. privateHashMap<String,Object>map;
  19. @Override
  20. protectedvoidonCreate(BundlesavedInstanceState){
  21. super.onCreate(savedInstanceState);
  22. setContentView(R.layout.testsimpleadapter);
  23. mListView=(ListView)findViewById(R.id.mySimpleList);
  24. mAdapter=newSimpleAdapter(this,getData(),R.layout.simpleitem,newString[]{"image","title","info"},newint[]{R.id.img,R.id.title,R.id.info});
  25. mListView.setAdapter(mAdapter);
  26. }
  27. privateList<HashMap<String,Object>>getData(){
  28. mHashMaps=newArrayList<HashMap<String,Object>>();
  29. map=newHashMap<String,Object>();
  30. map.put("image",R.drawable.gallery_photo_1);
  31. map.put("title","G1");
  32. map.put("info","google1");
  33. mHashMaps.add(map);
  34. map=newHashMap<String,Object>();
  35. map.put("image",R.drawable.gallery_photo_2);
  36. map.put("title","G2");
  37. map.put("info","google2");
  38. mHashMaps.add(map);
  39. map=newHashMap<String,Object>();
  40. map.put("image",R.drawable.gallery_photo_3);
  41. map.put("title","G3");
  42. map.put("info","google3");
  43. mHashMaps.add(map);
  44. returnmHashMaps;
  45. }
  46. }

simpleAdapter的数据都是用HashMap构成的List,List里面的每一节对应的是ListView的没一行,这里先建一个HashMap构成的List,布局中有3个元素,ImageView,2个TextView,每个item项的布局文件如下:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:orientation="horizontal">
  7. <ImageView
  8. android:layout_width="wrap_content"
  9. android:id="@+id/img"
  10. android:layout_margin="5px"
  11. android:layout_height="wrap_content">
  12. </ImageView>
  13. <LinearLayout
  14. android:id="@+id/linearLayout1"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:orientation="vertical">
  18. <TextView
  19. android:id="@+id/title"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:textColor="#ffffff"
  23. android:textSize="22px"></TextView>
  24. <TextView
  25. android:id="@+id/info"
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"
  28. android:textColor="#ffffff"
  29. android:textSize="13px"></TextView>
  30. </LinearLayout>
  31. </LinearLayout>

所以有了HashMap构成的数组后,我们要在HashMap中加入数据,按顺序加入图片,titleinfo,一个HashMap就构成了ListView中的一个Item项,我们在看下API中是怎么描述simpleAdapter的:


第一个参数和第三个参数跟ArrayAdapter中的是一样的,第二个参数就是由HashMap组成的List,也就是数据源,而第5个参数也就是map中的key,最后一个参数就是map中key对应的值要显示在布局中的位置的id。

看下效果:


如果我们想在每个Item中加个button,而且点击button有对应的操作,那该怎么办呢。

这时我们可以重写baseAdapter,看代码:

  1. packagecom.shang.test;
  2. importjava.util.ArrayList;
  3. importjava.util.HashMap;
  4. importjava.util.List;
  5. importandroid.app.Activity;
  6. importandroid.app.AlertDialog;
  7. importandroid.content.Context;
  8. importandroid.content.DialogInterface;
  9. importandroid.os.Bundle;
  10. importandroid.view.LayoutInflater;
  11. importandroid.view.View;
  12. importandroid.view.View.OnClickListener;
  13. importandroid.view.ViewGroup;
  14. importandroid.widget.BaseAdapter;
  15. importandroid.widget.Button;
  16. importandroid.widget.ImageView;
  17. importandroid.widget.ListView;
  18. importandroid.widget.TextView;
  19. /**
  20. *
  21. *@authorshangzhenxiang
  22. *
  23. */
  24. publicclassTestBaseAdapterextendsActivity{
  25. privateListViewmListView;
  26. @Override
  27. protectedvoidonCreate(BundlesavedInstanceState){
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.baseadapterlist);
  30. mListView=(ListView)findViewById(R.id.baselist);
  31. mListView.setAdapter(newBaseListAdapter(this));
  32. }
  33. privateList<HashMap<String,Object>>getData(){
  34. List<HashMap<String,Object>>maps=newArrayList<HashMap<String,Object>>();
  35. HashMap<String,Object>map=newHashMap<String,Object>();
  36. map.put("image",R.drawable.gallery_photo_1);
  37. map.put("title","G1");
  38. map.put("info","google1");
  39. maps.add(map);
  40. map=newHashMap<String,Object>();
  41. map.put("image",R.drawable.gallery_photo_2);
  42. map.put("title","G2");
  43. map.put("info","google2");
  44. maps.add(map);
  45. map=newHashMap<String,Object>();
  46. map.put("image",R.drawable.gallery_photo_3);
  47. map.put("title","G3");
  48. map.put("info","google3");
  49. maps.add(map);
  50. returnmaps;
  51. }
  52. privateclassBaseListAdapterextendsBaseAdapterimplementsOnClickListener{
  53. privateContextmContext;
  54. privateLayoutInflaterinflater;
  55. publicBaseListAdapter(ContextmContext){
  56. this.mContext=mContext;
  57. inflater=LayoutInflater.from(mContext);
  58. }
  59. @Override
  60. publicintgetCount(){
  61. returngetData().size();
  62. }
  63. @Override
  64. publicObjectgetItem(intposition){
  65. returnnull;
  66. }
  67. @Override
  68. publiclonggetItemId(intposition){
  69. return0;
  70. }
  71. @Override
  72. publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
  73. ViewHolderviewHolder=null;
  74. if(convertView==null){
  75. viewHolder=newViewHolder();
  76. convertView=inflater.inflate(R.layout.testbaseadapter,null);
  77. viewHolder.img=(ImageView)convertView.findViewById(R.id.img);
  78. viewHolder.title=(TextView)convertView.findViewById(R.id.title);
  79. viewHolder.info=(TextView)convertView.findViewById(R.id.info);
  80. viewHolder.button=(Button)convertView.findViewById(R.id.basebutton);
  81. convertView.setTag(viewHolder);
  82. }else{
  83. viewHolder=(ViewHolder)convertView.getTag();
  84. }
  85. System.out.println("viewHolder="+viewHolder);
  86. viewHolder.img.setBackgroundResource((Integer)getData().get(position).get("image"));
  87. viewHolder.title.setText((CharSequence)getData().get(position).get("title"));
  88. viewHolder.info.setText((CharSequence)getData().get(position).get("info"));
  89. viewHolder.button.setOnClickListener(this);
  90. returnconvertView;
  91. }
  92. classViewHolder{
  93. ImageViewimg;
  94. TextViewtitle;
  95. TextViewinfo;
  96. Buttonbutton;
  97. }
  98. @Override
  99. publicvoidonClick(Viewv){
  100. intid=v.getId();
  101. switch(id){
  102. caseR.id.basebutton:
  103. showInfo();
  104. break;
  105. }
  106. }
  107. privatevoidshowInfo(){
  108. newAlertDialog.Builder(TestBaseAdapter.this).setTitle("mylistview").setMessage("introduce....").
  109. setPositiveButton("OK",newDialogInterface.OnClickListener(){
  110. @Override
  111. publicvoidonClick(DialogInterfacedialog,intwhich){
  112. //TODOAuto-generatedmethodstub
  113. }
  114. }).show();
  115. }
  116. }
  117. }

再看下面Item布局文件:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:orientation="horizontal">
  7. <ImageView
  8. android:layout_width="wrap_content"
  9. android:id="@+id/img"
  10. android:layout_margin="5px"
  11. android:layout_height="wrap_content">
  12. </ImageView>
  13. <LinearLayout
  14. android:id="@+id/linearLayout1"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:orientation="vertical">
  18. <TextView
  19. android:id="@+id/title"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:textColor="#ffffff"
  23. android:textSize="22px"></TextView>
  24. <TextView
  25. android:id="@+id/info"
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"
  28. android:textColor="#ffffff"
  29. android:textSize="13px"></TextView>
  30. </LinearLayout>
  31. <Button
  32. android:id="@+id/basebutton"
  33. android:text="more"
  34. android:focusable="false"
  35. android:layout_gravity="bottom|right"
  36. android:layout_height="wrap_content"
  37. android:layout_width="wrap_content"/>
  38. </LinearLayout>

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

  如果我们要自定义适配器,那就要重写getView方法,getView()有三个参数,position表示将显示的是第几行,covertView是从布局文件中inflate来的布局。我们写一个类来描述布局文件中的各个组件,比如ImageView,TextView等,然后判断convertView是否为空,如果为空就从inflate中拿到布局,并新建一个ViewHolder,然后从convertView中拿到布局中的各个组件,同时把ViewHolder放到tag中去,下次就不用重写new了,直接从tag中拿就可以了,然后把布局中的各个组件都设上对应的值,这里的Position对应到含有HashMap的List中的position。

在实际的运行过程中会发现listView的每一行没有焦点了,这是因为Button抢夺了listView的焦点,只要布局文件中将Button设置为没有焦点就OK了。

看下运行效果:

分享到:
评论

相关推荐

    Android开发笔记之Adapter用法

    三个示例代码,分别演示了ArrayAdapter,SimpleAdapter,和BaseAdapter的用法。

    Android开发之搜索框SearchView用法示例

    本文实例讲述了Android开发之搜索框SearchView用法。分享给大家供大家参考,具体如下: 介绍: SearchView时搜索组件,可以让用户输入文字,见他输入匹配结果 效果: 基本的用法 我就不详细描述了 这里主要说一些我...

    Android开发案例驱动教程 配套代码

    《Android开发案例驱动教程》 配套代码。 注: 由于第12,13,14章代码太大,无法上传到一个包中。 这三节代码会放到其他压缩包中。 作者:关东升,赵志荣 Java或C++程序员转变成为Android程序员 采用案例驱动模式...

    Android代码-Android开发常用整理

    Android开发常用整理(不断扩充中)包含各种工具类、线程池、日志、自定义的控件、程序崩溃捕捉处理、默认的Application配置、常用的Adapter等 注意: &gt; 如果需要使用FragmentTabAdapter,则需要android-support-v4....

    Android高级编程--源代码

    因为没有了人为制造的障碍,所以Android开发人员可以自由地编写能够充分利用日益强大的手机硬件的应用程序。因此,对Android感兴趣的开发人员都把Google在2008年发布Android这一举措作为移动技术发展史上的一个非常...

    Android移动应用开发实验指导书.docx

    (3)掌握自定义控件的2种使用方法。 (4)掌握ListView的简单用法。 (5)掌握自定义ListView控件的使用。 实验软、硬件环境 硬件:PC电脑一台; 配置:winxp或win7系统,内存大于4G,硬盘250G及以上 JDK1.7 、...

    Android开发中动态获取RecyclerView的Item中EditText的内容

    我们在实际开发中,可能会遇到要在列表里面放入一个EditText,但是我们在列表所在的界面获取不到这个EditText的值,所以,这里我们在Adapter里面为EditText添加一个addTextChangedListener,并实现TextWatcher接口来...

    Android编程开发之Spinner组件用法

    本文实例讲述了Android编程开发之Spinner组件用法。分享给大家供大家参考,具体如下: Spinner组件组要用显示一个下拉列表,在使用中需要用到适配器Adapter,下面是一个该组件的使用示例 首先是布局文件main.xml: ...

    Google Android SDK开发范例大全(PDF完整版4)(4-4)

    Google Android SDK开发范例大全(完整版)共4个分卷 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1...

    Google Android SDK开发范例大全(PDF高清完整版1)(4-1)

    Google Android SDK开发范例大全(完整版)共4个分卷 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1...

    Android开发指南中文版

    16 线程安全方法 .................................................................................................. 17 组件生命周期 .......................................................................

    Google Android SDK开发范例大全(PDF高清完整版3)(4-3)

    Google Android SDK开发范例大全(完整版)共4个分卷 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1...

    基于Eclipse的 Android Adapter在ListView和GridView中的应用

    ListView的简单介绍与使用 GridView的简单介绍与使用 自定义BaseAdapter BaseAdapter的三种使用方式 ...BaseAdapter:抽象类,实际开发中我们会继承这个类并且重写相关方法,用得最多的一个Adapter!

    Google Android SDK开发范例大全的目录

    4.22 加载手机磁盘里的图文件——使用decodeFile方法 4.23 动态放大缩小ImageView里的图片——运用Matrix对象来缩放图文件 4.24 动态旋转图片——Bitmap与Matrix旋转ImageView 4.25 猜猜我在想什么——RadioButtonID...

    Android开发指南中文版.pdf 清晰版

    Android开发指南中文版 目录 应用程序基础Application Fundamentals................................ 4 关键类................................................................ 4 应用程序组件..................

    Android开发宝典.rar

    使用意图匹配Using intent matching 52 数据存储Data Storage 52 概览Storage quickview 52  系统偏好:快速,轻量级存储 52  文件:存储到设备内部或可移动闪存 52  数据库:任意的结构化存储 52  ...

    Android UI组件实例集合

    使用方法:1-把GifView.jar加入你的项目。2-在xml中配置GifView的基本属性,GifView继承自View类,和Button、ImageView一样是一个UI控件。 如: &lt;com.ant.liao.GifView android:id="@+id/gif2" android:layout_...

    Android开发之ListView、GridView 详解及示例代码

    ListView与GridView是Android开发中的常用控件,它们和Adapter配合使用能够实现很多界面效果。下面分别以实例说明ListView、GridView的用法。  1.ListView的Android开发实例  ListView 是android开发中最常用的...

Global site tag (gtag.js) - Google Analytics