文档详情

Android-listview与adapter用法(补汉6个汉字字).docx

发布:2018-12-24约2.42万字共35页下载文档
文本预览下载声明
HYPERLINK /zhengbeibei/archive/2013/05/14/3078805.html Android listview与adapter用法 HYPERLINK /blog/1675509 listview与adapter用法 博客分类:? HYPERLINK /category/239377 android ? ? 一个ListView通常有两个职责。 (1)将数据填充到布局。 (2)处理用户的选择点击等操作。 第一点很好理解,ListView就是实现这个功能的。第二点也不难做到,在后面的学习中读者会发现,这非常简单。 一个ListView的创建需要3个元素。 (1)ListView中的每一列的View。 (2)填入View的数据或者图片等。 (3)连接数据与ListView的适配器。 也就是说,要使用ListView,首先要了解什么是适配器。适配器是一个连接数据和AdapterView(ListView就是一个典型的AdapterView,后面还会学习其他的)的桥梁,通过它能有效地实现数据与AdapterView的分离设置,使AdapterView与数据的绑定更加简便,修改更加方便 Android中提供了很多的Adapter,表4-5列出了常用的几个。 表4-5?常用适配器 Adapter 含义 ArrayAdapterT 用来绑定一个数组,支持泛型操作 SimpleAdapter 用来绑定在xml中定义的控件对应的数据 SimpleCursorAdapter 用来绑定游标得到的数据 BaseAdapter 通用的基础适配器 ? ?其实适配器还有很多,要注意的是,各种Adapter只不过是转换的方式和能力不一样而已。下面就通过使用不同的Adapter来为ListView绑定数据(SimpleCursorAdapter暂且不讲,后面讲SQLite时会介绍)。 4.12.1 ListView使用ArrayAdapter 用ArrayAdapter可以实现简单的ListView的数据绑定。默认情况下,ArrayAdapter绑定每个对象的toString值到layout中预先定义的TextView控件上。ArrayAdapter的使用非常简单。 实例: 工程目录:EX_04_12 在布局文件中加入一个ListView控件。 ?xmlversion=1.0encoding=utf-8? LinearLayoutxmlns:android= /apk/res/android android:layout_width=fill_parent ? android:layout_height=fill_parent !-- 添加一个ListView控件 -- ListView android:id=@+id/lv android:layout_width=fill_parent android:layout_height=fill_parent/ ? /LinearLayout 然后在Activity中初始化。 publicclass MyListView extends Activity { private static final String[] strs = new String[] { first, second, third, fourth, fifth };//定义一个String数组用来显示ListView的内容 private ListView lv;/** Called when the activity is first created. */ @Override publicvoid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lv = (ListView) findViewById(R.id.lv);//得到ListView对象的引用 /*为ListView设置Adapter来绑定数据*/? lv.setAdapter(new ArrayAdapterString(this, android.R.layout.simple_list_item_1, strs)); } } ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ???? ▲图4-29 ListView使用ArrayAdapter运行效果
显示全部
相似文档