ListView及ListAdapter详解

ListView及ListAdapter详解

一、AdapterView

1. 简介

An AdapterView is a view whose children are determined by an Adapter.

简单地说就是其子视图是由适配器决定的视图组件

2. 子类

  • ListView
  • GridView
  • Spinner
  • Gallery

3. 常用方法

//功能:获取list中指定位置item
getItemAtPosition(int position) 
//功能:获取list中指定位置item 的id
getItemIdAtPosition(int position) 
//功能:Sets the adapter that provides the data and the views to represent the data in this widget.
//翻译:设置提供数据和显示数据的视图的适配器
setAdapter(T adapter) 
//功能:Sets the view to show if the adapter is empty
//翻译:设置当适配器没数据时的视图
setEmptyView(View emptyView) 
//功能:获取选中的item
getSelectedItem()  
//功能:获取选中的item的id
long getSelectedItemId()  
//功能:获取选中的item在数据集中的位置 
int getSelectedItemPosition() 
//功能:Call the OnItemClickListener, if it is defined.
//翻译:调用列表项点击事件,如果定义了的话
performItemClick(View view, int position, long id) 
//功能:设置当前选中的item
setSelection(int position) 
//功能:Register a callback to be invoked when this view is clicked.
//翻译:给视图设置点击事件
setOnClickListener(View.OnClickListener l) 
//功能:Register a callback to be invoked when an item in this AdapterView has been clicked.
//翻译:给适配器视图中的一项设置点击事件
setOnItemClickListener(AdapterView.OnItemClickListener listener) 
//功能:Register a callback to be invoked when an item in this AdapterView has been clicked and held
//翻译:给适配器视图中的一项设置长按事件
setOnItemLongClickListener(AdapterView.OnItemLongClickListener listener) 
//功能:Register a callback to be invoked when an item in this AdapterView has been selected.
//翻译:给适配器视图中的一项设置选中事件
setOnItemSelectedListener(AdapterView.OnItemSelectedListener listener) 

二、ListView

1. 简介

继承关系

这里写图片描述

以列表滚动形式显示数据内容,数据内容来自ListAdapter,根据数据长度适应屏幕显示

2. XML属性

Attribute NameDescription
android:dividerDrawable or color to draw between list items. (列表项的分隔线)
android:dividerHeightHeight of the divider. (分隔线的高度)
android:entriesReference to an array resource that will populate the ListView. (关联的数组资源)
android:footerDividersEnabledWhen set to false, the ListView will not draw the divider before each footer view. (是否要在底部视图下方也添加分隔线)
android:headerDividersEnabledWhen set to false, the ListView will not draw the divider after each header view. (是否要在头部视图下方也添加分隔线)

3. 方法

/**
*功能:Sets the data behind this ListView.(设置ListView的适配器)
*参数adapter:一个ListAdapter,提供支持listview背后的数据并产生列表项视图
*/
setAdapter(ListAdapter adapter);
/**
*功能:Add a fixed view to appear at the bottom of the list.(添加底部视图)
*参数v:要添加的视图
*/
 addFooterView(View v) ;
/**
*功能:Add a fixed view to appear at the bottom of the list.(添加底部视图)
*参数v:要添加的视图
*参数data: Data to associate with this view (跟视图关联的数据)有什么用?关联的数据可以通过getCount方法获取
*参数isSelectable :true if the footer view can be selected(视图是否能被选)
*/
addFooterView(View v, Object data, boolean isSelectable) ;
/**
*功能:Add a fixed view to appear at the bottom of the list.(添加头部视图)
*参数v:要添加的视图
*/
addHeaderView(View v) ;
/**
*功能:Add a fixed view to appear at the bottom of the list.(添加头部部视图)
*参数v:要添加的视图
*参数data: Data to associate with this view (跟视图关联的数据)有什么用?关联的数据可以通过getCount方法获取
*参数isSelectable :true if the footer view can be selected(视图是否能被选)
*/
addHeaderView(View v, Object data, boolean isSelectable) ;

三、Adapter接口

1. 简介

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.

就是说,适配器对象就是适配器视图和背后的数据的桥梁。适配器提供数据项的接口,也负责给每个数据项设置视图。

2. 方法

/**
*功能:How many items are in the data set represented by this Adapter.(获取条目数)
*点击事件会触发getCount();
*在新建view之前和之后会调用几次getCount()
*条目数包括头部视图和底部视图
*/
getCount();
/**
*功能:Get a View that displays the data at the specified position in the data set.(决定每个列表项的数据和视图显示)
*参数position: The position of the item within the adapter's data set of the item whose view we want.
*参数convertView: The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using. If it is not possible to convert this view to display the correct data, this method can create a new view. Heterogeneous lists can specify their number of view types, so that this View is always of the right type (see getViewTypeCount() and getItemViewType(int)).
*参数parent : The parent that this view will eventually be attached to 
*/
getView(int position, View convertView, ViewGroup parent);
//Get the data item associated with the specified position in the data set. 
getItem(int position) 
//Get the row id associated with the specified position in the list. 
getItemId(int position) 
//true if this adapter doesn't contain any data. This is used to determine whether the empty view should be displayed. A typical implementation will return getCount() == 0 but since getCount() includes the headers and footers, specialized adapters might want a different behavior.
isEmpty()

四、ListAdapter接口

1. 简介

ListView和数据之间的桥梁,通常数据来源于一个Cursor(游标),ListView显示包装在ListAdapter中的数据。其实现类如下

这里写图片描述

2. 实现类

2.1 BaseAdapter
  1. 简介

    是一个抽象类,需要重写View getView(int position, View convertView, ViewGroup parent)int getCount()long getItemId(int position)Object getItem(int position)四个方法,可以做复杂的布局。

  2. 理解
    调用getView方法返回的是一个列表项视图,可以是ViewGroup,也可以是View。而ConvertView就是是被指向界面显示的第一个View的上一个View ,即刚刚被滑出界面的View;这个ConvertView的类型要跟getView返回值保持一致,否则会抛出类型转换异常;通过复用CovertView,达到优化ListView性能的目的。怎么复用呢?很简单,只要就行ConvertView的非空判断,然后将其赋值给我们自定义的列表项视图,为空的话才创建自定义的列表项视图。

  3. 实例

    /*
    * MainActivity.java中的核心代码
    * lv为一个ListView
    * list为一个ArrayList<Integer>,存放图片的资源id
    */
    lv.setAdapter(new BaseAdapter() {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View v = null;
                if (convertView != null) {
                    v = convertView;
                } else {
                    v = LayoutInflater.from(getApplicationContext()).inflate(
                            R.layout.listview_base, null);
                }
                ImageView img = (ImageView) v.findViewById(R.id.imgBase);
                img.setImageResource(list.get(position));
                return v;
            }
            @Override
            public long getItemId(int position) {
                return position;
            }
            @Override
            public Object getItem(int position) {
                return list.get(position);
            }
            @Override
            public int getCount() {
                return list.size();
            }
        });
    <!--这是listview_base.xml-->  
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ImageView
        android:id="@+id/imgArray"
        android:layout_width="match_parent"
        android:layout_height="200dp" >
    </ImageView>
    </LinearLayout>
2.2 ArrayAdapter
  1. 简介
    是BaseAdapter的子类,是具体类。默认的资源ID指向单个的TextView,当然你可以用其他构造方法,传入一个更大的布局,这样你就可以在一个指向一个更大的布局中的TextView。或者你想要的是指向ImageView,而不是TextView,这时候你就不得不重写getView方法了

  2. 构造方法

    这里写图片描述

    参数说明

    • context 上下文
    • resource 包含textView的布局文件id
    • textViewResourceId textView的id
    • objects 数据集,数组或List集合
  3. 实例

    /*
    * MainActivity.java中的核心代码
    * lv为一个ListView
    * list为一个ArrayList<Integer>,存放图片的资源id
    */
    lv.setAdapter(new ArrayAdapter<Integer>(MainActivity.this,
                R.layout.listview_array, list) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view=null;
                if (convertView != null) {
                    view = convertView;
                } else {
                    view = LayoutInflater.from(getContext()).inflate(R.layout.listview_array, null);
                }
                ImageView imgArray = (ImageView) view.findViewById(
                        R.id.imgArray);
                imgArray.setImageResource(list.get(position));
                return view;
            }
        });
    <!--这是listview_array.xml-->
    <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/imgArray"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:scaleType="centerInside" >
    </ImageView>
    //问题:不知道为什么xml中宽高设置并不生效?
    //解答:ImageView外围再包裹一个Layout就可以了。
2.3 SimpleAdapter
  1. 简介
    是BaseAdapter的子类,是具体类。不想自定义适配器,又要做复杂布局时用。可以处理一般的组件与数据的绑定。

  2. 构造方法

    /**
    * 参数context:上下文对象
    * 参数data:用于绑定到视图的列表项为map的list
    * 参数resource:包裹视图的资源文件id
    * 参数from:map中要连接到视图的字段名(key)数组
    * 参数to:与from对应的视图组件的id数组
    */
    SimpleAdapter(Context context, List<? extends Map<String,?>> data, int resource, String[] from, int[] to) 
    1. 实例
    /*
    * MainActivity.java中的核心代码
    * lv为一个ListView
    * list为一个ArrayList<Integer>,存放图片的资源id
    */
    List<LinkedHashMap<String, Object>> data = new ArrayList<LinkedHashMap<String,Object>>();
        for (Integer i : list) {
            LinkedHashMap<String, Object> map =  new LinkedHashMap<String, Object>();
            map.put("img", i);
            data.add(map);
        }
        lv.setAdapter(new SimpleAdapter(this, data, R.layout.listview_simple, new String[]{"img"}, new int[]{R.id.imgSimple}));
    <!--这是listview_simple.xml-->        
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ImageView
        android:id="@+id/imgSimple"
        android:layout_width="match_parent"
        android:layout_height="200dp" >
    </ImageView>
    </LinearLayout>
2.4 SimpleCursorAdapter
  1. 简介

    An easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file. You can specify which columns you want, which views you want to display the columns, and the XML file that defines the appearance of these views.

    简单地说,就是一个类似于SimpleAdapter的适配器,只是它的数据源是一个cursor对象。

  2. 构造方法

    /**
    * 参数context:上下文对象
    * 参数layout:包裹视图的资源文件id
    * 参数c:数据库的Cursor对象
    * 参数from:需要的字段名数组
    * 参数to:与from对应的要绑定的视图id数组
    * 参数flags:定义CursorAdapter的行为,FLAG_REGISTER_CONTENT_OBSERVER表示注册内容观察者
    */
    SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from,
            int[] to, int flags)
  3. 实例

    /*
    * MainActivity.java中的核心代码
    * lv为一个ListView
    *db为一个SQLiteDatabase对象
    * 数据库中的表必须要有自增长的字段“_id”,而且查询时也必须查出它
    * 但是我们可以通过“id as _id”的方式解决我们数据表里用id用自增的问题
    */
    String sql ="select id as _id,rid from imgs";
        Cursor c = db.rawQuery(sql, null);
        lv.setAdapter(new SimpleCursorAdapter(
                this,
                R.layout.listview_simple,
                c, 
                new String[]{"rid"},
                new int[]{R.id.imgSimple}, CursorAdapter.NO_SELECTION));
    <!--布局文件同上-->

五、ViewHolder

由于理解还不是很充足,暂时不说,下次更新…

  • 17
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来详细介绍一下ListView和CycleView。 1. ListView ListViewAndroid提供的一个用于展示长列表数据的控件。它可以通过Adapter来动态加载数据,并且支持滚动、选中、点击等基本操作。ListView的优点是可以自动回收不可见的子视图,以便节省内存,同时也可以通过设置缓存策略来提高性能。 ListView的使用步骤如下: 1)在布局文件中添加ListView控件。 2)创建一个Adapter,实现getView()方法,用于动态加载数据。 3)在代码中调用setAdapter()方法,将Adapter绑定到ListView上。 4)通过setOnItemClickListener()方法来监听ListView子项的点击事件。 2. CycleView CycleView是一个可循环滚动的视图容器,也称为轮播图。它通常用于在界面中展示多张图片或广告,自动进行滚动切换,使得用户能够快速浏览内容。CycleView的实现方式有多种,可以使用ViewPager、RecyclerView等控件进行实现。 CycleView的使用步骤如下: 1)在布局文件中添加ViewPager控件。 2)创建一个Adapter,实现instantiateItem()方法,用于动态加载数据。 3)在代码中调用setAdapter()方法,将Adapter绑定到ViewPager上。 4)通过Handler和Runnable实现自动轮播功能。 5)通过ViewPager的addOnPageChangeListener()方法来监听当前页面的变化,以便在需要时进行相应的处理。 总的来说,ListView适合展示长列表数据,而CycleView则适合展示多张图片或广告等内容。两者都是Android中常用的视图控件,开发者可以根据自己的需求选择合适的控件进行使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值