1、ListView简单用法
(1)首先在main_activity.xml中加入ListView控件

(2)修改活动MainActivity代码

设置适配器,这里我选用的是ArrayAdapter适配器,它可以通过泛型 来指定要适配的数据类型,然后在构造函数中把要适配的数据传入。这里要注意一下arrayadapter()方法,ArrayAdapter(Context context ,int textViewResourceId ,List<T> objects)
context ----> The current context ,上下文,就是当前的Activity
textViewResourceId ---->the resource ID for a layout file contain a TextView to use when instantiating views,Android sdk中自己内置的一个布局,它里面只有一个TextView,这个参数是表明我们数组中每一条数据的布局是这个View,就是将每一条数据都显示在这个View上面,也就是当装载在这个构造函数中的layout时,其layout的ID 必须是一个TextView,简言之,第2个参数应该是ListView中每个选择项的样式,可以使用系统自带的 android.R.layout.xxx,也可以是自定义的,仅包含TextView。
List<T> objects ---> the objects to represent in the ListView,就是我们要显示的数据。listView会根据这三个参数,遍历AdapterData里面的每一条数据,读出一条,显示到第二个参数对应的布局中,这样就形成了我们看到的ListView.
当在加载布局item_layout时,要注意其xml文件要以TextView为根节点,不然就会抛“ArrayAdapter requires the resource ID to be a TextView”

2、定制ListView界面
(1)定义实体类,作为适配器的适配类型
public class Fruit {
private String name;
private int imageId;
public Fruit(String name,int imageId){
this.name=name;
this.imageId=imageId;
}
public String getName(){
return name;
}
public int getImageId(){
return image

本文介绍了Android中ListView的基本使用,包括设置ArrayAdapter、自定义ListView的界面以及如何提高性能。通过定义实体类和自定义布局,实现了显示带有图片和文本的列表项。此外,还讨论了ListView的优化,如重用convertView和使用ViewHolder技术减少查找控件的时间。最后,添加了点击事件监听,展示了如何处理用户的点击操作。
最低0.47元/天 解锁文章
3072

被折叠的 条评论
为什么被折叠?



