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

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

下面先来看看ArrayAdapter:

[java] view
plain
copy

  1. package com.shang.test;
  2. import java.util.ArrayList;
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.widget.ArrayAdapter;
  6. import android.widget.ListView;
  7. /**
  8. *
  9. * @author shangzhenxiang
  10. *
  11. */
  12. public class TestArrayAdapterActivity extends Activity{
  13. private ListView mListView;
  14. private ArrayList<String> mArrayList = new ArrayList<String>();
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.testarrayadapter);
  19. mListView = (ListView) findViewById(R.id.myArrayList);
  20. mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, getData()));
  21. }
  22. private ArrayList<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. return mArrayList;
  30. }
  31. }

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

[html] view
plain
copy

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns: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上。

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

[java] view
plain
copy

  1. package com.shang.test;
  2. import android.app.Activity;
  3. import android.database.Cursor;
  4. import android.os.Bundle;
  5. import android.provider.Contacts.People;
  6. import android.widget.ListView;
  7. import android.widget.SimpleCursorAdapter;
  8. /**
  9. *
  10. * @author shangzhenxiang
  11. *
  12. */
  13. public class TestSimpleCursorAdapter extends Activity {
  14. private ListView mListView;
  15. private Cursor mCursor;
  16. private SimpleCursorAdapter mAdapter;
  17. @Override
  18. protected void onCreate(Bundle savedInstanceState) {
  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 = new SimpleCursorAdapter(TestSimpleCursorAdapter.this, android.R.layout.simple_expandable_list_item_1, mCursor, new String[]{People.NAME}, new int[]{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文件中是这么写的:

[java] view
plain
copy

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!-- Copyright (C) 2006 The Android Open Source Project
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. -->
  13. <TextView xmlns: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,扩展性好,可以定义各种各样的布局。

代码如下:

[java] view
plain
copy

  1. package com.shang.test;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import android.app.Activity;
  6. import android.os.Bundle;
  7. import android.widget.ListView;
  8. import android.widget.SimpleAdapter;
  9. /**
  10. *
  11. * @author shangzhenxiang
  12. *
  13. */
  14. public class TestSimpleAdapter extends Activity {
  15. private ListView mListView;
  16. private SimpleAdapter mAdapter;
  17. private List<HashMap<String, Object>> mHashMaps;
  18. private HashMap<String, Object> map;
  19. @Override
  20. protected void onCreate(Bundle savedInstanceState) {
  21. super.onCreate(savedInstanceState);
  22. setContentView(R.layout.testsimpleadapter);
  23. mListView = (ListView) findViewById(R.id.mySimpleList);
  24. mAdapter = new SimpleAdapter(this, getData(), R.layout.simpleitem, new String[]{"image", "title", "info"}, new int[]{R.id.img, R.id.title, R.id.info});
  25. mListView.setAdapter(mAdapter);
  26. }
  27. private List<HashMap<String, Object>> getData() {
  28. mHashMaps = new ArrayList<HashMap<String,Object>>();
  29. map = new HashMap<String, Object>();
  30. map.put("image", R.drawable.gallery_photo_1);
  31. map.put("title", "G1");
  32. map.put("info", "google 1");
  33. mHashMaps.add(map);
  34. map = new HashMap<String, Object>();
  35. map.put("image", R.drawable.gallery_photo_2);
  36. map.put("title", "G2");
  37. map.put("info", "google 2");
  38. mHashMaps.add(map);
  39. map = new HashMap<String, Object>();
  40. map.put("image", R.drawable.gallery_photo_3);
  41. map.put("title", "G3");
  42. map.put("info", "google 3");
  43. mHashMaps.add(map);
  44. return mHashMaps;
  45. }
  46. }

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

[java] view
plain
copy

  1. <?xml version="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中加入数据,按顺序加入图片,title,info,一个HashMap就构成了ListView中的一个Item项,我们在看下API中是怎么描述simpleAdapter的:

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

看下效果:

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

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

[java] view
plain
copy

  1. package com.shang.test;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import android.app.Activity;
  6. import android.app.AlertDialog;
  7. import android.content.Context;
  8. import android.content.DialogInterface;
  9. import android.os.Bundle;
  10. import android.view.LayoutInflater;
  11. import android.view.View;
  12. import android.view.View.OnClickListener;
  13. import android.view.ViewGroup;
  14. import android.widget.BaseAdapter;
  15. import android.widget.Button;
  16. import android.widget.ImageView;
  17. import android.widget.ListView;
  18. import android.widget.TextView;
  19. /**
  20. *
  21. * @author shangzhenxiang
  22. *
  23. */
  24. public class TestBaseAdapter extends Activity {
  25. private ListView mListView;
  26. @Override
  27. protected void onCreate(Bundle savedInstanceState) {
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.baseadapterlist);
  30. mListView = (ListView) findViewById(R.id.baselist);
  31. mListView.setAdapter(new BaseListAdapter(this));
  32. }
  33. private List<HashMap<String, Object>> getData() {
  34. List<HashMap<String, Object>> maps = new ArrayList<HashMap<String,Object>>();
  35. HashMap<String, Object> map = new HashMap<String, Object>();
  36. map.put("image", R.drawable.gallery_photo_1);
  37. map.put("title", "G1");
  38. map.put("info", "google 1");
  39. maps.add(map);
  40. map = new HashMap<String, Object>();
  41. map.put("image", R.drawable.gallery_photo_2);
  42. map.put("title", "G2");
  43. map.put("info", "google 2");
  44. maps.add(map);
  45. map = new HashMap<String, Object>();
  46. map.put("image", R.drawable.gallery_photo_3);
  47. map.put("title", "G3");
  48. map.put("info", "google 3");
  49. maps.add(map);
  50. return maps;
  51. }
  52. private class BaseListAdapter extends BaseAdapter implements OnClickListener {
  53. private Context mContext;
  54. private LayoutInflater inflater;
  55. public BaseListAdapter(Context mContext) {
  56. this.mContext = mContext;
  57. inflater = LayoutInflater.from(mContext);
  58. }
  59. @Override
  60. public int getCount() {
  61. return getData().size();
  62. }
  63. @Override
  64. public Object getItem(int position) {
  65. return null;
  66. }
  67. @Override
  68. public long getItemId(int position) {
  69. return 0;
  70. }
  71. @Override
  72. public View getView(int position, View convertView, ViewGroup parent) {
  73. ViewHolder viewHolder = null;
  74. if(convertView == null) {
  75. viewHolder = new ViewHolder();
  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. return convertView;
  91. }
  92. class ViewHolder {
  93. ImageView img;
  94. TextView title;
  95. TextView info;
  96. Button button;
  97. }
  98. @Override
  99. public void onClick(View v) {
  100. int id = v.getId();
  101. switch(id) {
  102. case R.id.basebutton:
  103. showInfo();
  104. break;
  105. }
  106. }
  107. private void showInfo() {
  108. new AlertDialog.Builder(TestBaseAdapter.this).setTitle("my listview").setMessage("introduce....").
  109. setPositiveButton("OK", new DialogInterface.OnClickListener() {
  110. @Override
  111. public void onClick(DialogInterface dialog, int which) {
  112. // TODO Auto-generated method stub
  113. }
  114. }).show();
  115. }
  116. }
  117. }

再看下面Item布局文件:

[java] view
plain
copy

  1. <?xml version="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的用法的更多相关文章

  1. Android开发之InstanceState详解

    Android开发之InstanceState详解   本文介绍Android中关于Activity的两个神秘方法:onSaveInstanceState() 和 onRestoreInstanceS ...

  2. 【Android UI】Android开发之View的几种布局方式及实践

    引言 通过前面两篇: Android 开发之旅:又见Hello World! Android 开发之旅:深入分析布局文件&又是“Hello World!” 我们对Android应用程序运行原理 ...

  3. Android开发之TextView高级应用

    Android开发之TextView高级应用 我们平时使用TextView往往让它作为一个显示文字的容器,但TextView的功能并不局限于此.以下就和大家分享一下TextView的一些使用技巧. A ...

  4. Android开发之InstanceState详解(转)---利用其保存Activity状态

    Android开发之InstanceState详解   本文介绍Android中关于Activity的两个神秘方法:onSaveInstanceState() 和 onRestoreInstanceS ...

  5. android开发之Animation(五)

    android开发之Animation的使用(五) 本博文主要讲述的是Animation中的AnimationLisenter的用法,以及此类的一些生命周期函数的调用,代码实比例如以下: MainAc ...

  6. Android开发之Java集合类性能分析

    对于Android开发者来说深入了解Java的集合类很有必要主要是从Collection和Map接口衍生出来的,目前主要提供了List.Set和 Map这三大类的集合,今天Android吧(ard8. ...

  7. Android开发之Git配置

    Android开发之Git配置 1.首先git配置: 输入命令: git config --global user.name "xxx.xx" git config --globa ...

  8. Android开发之旅: Intents和Intent Filters(理论部分)

    引言 大部分移动设备平台上的应用程序都运行在他们自己的沙盒中.他们彼此之间互相隔离,并且严格限制应用程序与硬件和原始组件之间的交互. 我们知道交流是多么的重要,作为一个孤岛没有交流的东西,一定毫无意义 ...

  9. Android开发之ViewPager+ActionBar+Fragment实现响应式可滑动Tab

     今天我们要实现的这个效果呢,在Android的应用中十分地常见,我们可以看到下面两张图,无论是系统内置的联系人应用,还是AnyView的阅读器应用,我们总能找到这样的影子,当我们滑动屏幕时,Tab可 ...

  10. Android开发之Java必备基础

    Android开发之Java必备基础 Java类型系统 Java语言基础数据类型有两种:对象和基本类型(Primitives).Java通过强制使用静态类型来确保类型安全,要求每个变量在使用之前必须先 ...

随机推荐

  1. 这届 Showgirl行不行?AI告诉你谁是ChinaJoy上最漂亮的小姐姐

    摘要: CJ开幕,顶着三伏天的酷暑高温,暴走一整天,就为了拍点漂亮小姐姐给大家看看. 一年一度的游戏视觉盛宴又来了! 作为一个游戏动漫控的肥宅,去CJ现场是必须的.除了看看游戏和动漫,各大游戏展台漂亮 ...

  2. Spark中直接操作HDFS

    Spark作为一个基于内存的大数据计算框架,可以和hadoop生态的资源调度器和分布式文件存储系统无缝融合.Spark可以直接操作存储在HDFS上面的数据: 通过Hadoop方式操作已经存在的文件目录 ...

  3. JsLint undeclared ‘window’

    如果使用IDEA 设置一下 globals 或 /*global window */ ... your script goes here https://stackoverflow.com/quest ...

  4. Qt数据库 QSqlTableModel实例操作(转)

    本文介绍的是Qt数据库 QSqlTableModel实例操作,详细操作请先来看内容.与上篇内容衔接着,不顾本文也有关于上篇内容的链接. Qt数据库 QSqlTableModel实例操作是本文所介绍的内 ...

  5. 035_go语言中的速率限制

    代码演示 package main import "fmt" import "time" func main() { requests := make(chan ...

  6. 006_go语言中的if else条件语句

    代码演示 package main import "fmt" func main() { if 7%2 == 0 { fmt.Println("7 is even&quo ...

  7. Layui+MVC+EF (项目从新创建开始)

    最近学习Layui ,就准备通过Layui来实现之前练习的项目, 先创建一个新的Web 空项目,选MVC 新建项目 创建各种类库,模块之间添加引用,并安装必要Nuget包(EF包)   模块名称 模块 ...

  8. Django 1.8.11 查询数据库返回JSON格式数据

    Django 1.8.11 查询数据库返回JSON格式数据 和前端交互全部使用JSON,如何将数据库查询结果转换成JSON格式 环境 Win10 Python2.7 Django 1.8.11 返回多 ...

  9. The Involution Principle

    目录 Catalan Paths Vandermonde Determinant The Pfaffian Catalan Paths 从 \((0,0)\) 走到 \((n,n)\), 每次只能向上 ...

  10. 谈谈MySql索引

    刚刚学习完丁奇老师<MySql 实战 45 讲>专栏中的索引部分,图文并茂的风格解开了我之前的许多疑惑,并且学习到许多新的东西,在此做个笔记,方便后续复习.由于 MySql 中存在多种存储 ...