【Andorid ListView】listview的分页、刷新总结

ListView的使用将会一直是android的一个重点。

首先说明listview的绘制过程。

getCount和getView都是adapter的必须实现的方法。

listView在开始绘制的时候,系统首先调用getCount()函数,根据他的返回值得到listView的长
度(这也是为什么在开始的第一张图特别的标出列表长度),然后根据这个长度,调用getView()逐
一绘制每一行。如果你的getCount()返回值是0的话,列表将不显示同样return 1,就只显示一行。
系统显示列表时,首先实例化一个适配器(这里将实例化自定义的适配器)。当手动完成适配时,必
须手动映射数据,这需要重写getView()方法。系统在绘制列表的每一行的时候将调用此方法。
getView()有三个参数,position表示将显示的是第几行,covertView是从布局文件中inflate来的
布局。我们用LayoutInflater的方法将定义好的main.xml文件提取成View实例用来显示。然后
将xml文件中的各个组件实例化(简单的findViewById()方法)。这样便可以将数据对应到各个组件
上了。但是按钮为了响应点击事件,需要为它添加点击监听器,这样就能捕获点击事件。至此一个自定
义的listView就完成了,现在让我们回过头从新审视这个过程。系统要绘制ListView了,他首先获得
要绘制的这个列表的长度,然后开始绘制第一行,怎么绘制呢?调用getView()函数。在这个函数里面
首先获得一个View(实际上是一个ViewGroup),然后再实例并设置各个组件,显示之。好了,绘制完
这一行了。那 再绘制下一行,直到绘完为止。在实际的运行过程中会发现listView的每一行没有焦点
了,这是因为Button抢夺了listView的焦点,只要布局文件中将Button设置为没有焦点就OK了。

关于listview的使用中有两种刷新,一种是“下拉刷新”和“上拉加载更多”,另外一种是“分页加载”。前者类似于腾讯和新浪微博,后者类似于百度贴吧。

关于后者比较简单一些,首先进行说明。

后者最初看起来比较复杂,但是其实是相当简单的。后者也有着它自己的使用范围。

例如:百度贴吧、以及一些需要分页显示的数据等等。

百度贴吧是实时性相当强的贴子聚集之地,所以需要使用分页来进行显示。

如果要写百度贴吧分页的话,就是相当简单的,将目前的页数作为参数发给服务器端,然后服务器返回一个json数据串。通过json数据串来显示。

如果是本地数据库分页显示的数据的话,那么更容易了,直接在adapter里面的getView()方法设置,并维护好index。

对于前者类似于腾讯和新浪微博,那么推荐使用的是

开源库pulltorefreshview。

之所以使用开源库的原因是在于开源库对于事件等已经封装的相当优秀了,不需要自己再写了。

使用开源库会出现的问题是:

如何将刷新后得到的多组数据添加到列表中。网上给出的demo只是一组数据。而现实中往往是多组数据的。

而且对于一些实时性较强的应用而言,它们的item是会发生改变的,尤其是社交应用。

暂时先不考虑item改变的情况。

将最基础的实现出来。

我的下拉刷新简单的demo效果如下,可以下拉刷新添加多项:

自己作为一个菜鸟想要学的快总是希望别人迅速提供博客的源码,但是总是遇到很坑爹。

这个项目的源码:http://download.csdn.net/detail/mcdullsin/8278079

首先看一下布局文件:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/pull_refresh_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:cacheColorHint="#00000000"
        android:divider="#19000000"
        android:dividerHeight="4dp"
        android:fadingEdge="none"
        android:fastScrollEnabled="false"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="false"
        android:smoothScrollbar="true" />

</LinearLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="horizontal"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent">
    
    
       <ImageView android:id="@+id/img"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_margin="5px"/>
    
       <LinearLayout android:orientation="vertical"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content">
    
           <TextView android:id="@+id/title"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:textSize="22sp" />
           <TextView android:id="@+id/info"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:textSize="13sp" />
    
       </LinearLayout>
   </LinearLayout>

MainActivity.java

package com.example.listviewdemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.example.listviewdemo.adapter.*;

public class MainActivity extends Activity {
    private List<Map<String, Object>> mData;
    private PullToRefreshListView listview;
    private ListViewAdapter mAdapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        listview =(PullToRefreshListView)findViewById(R.id.pull_refresh_list);
        mData = getData();
        mAdapter = new ListViewAdapter(this.getApplicationContext(),mData);
        listview.setAdapter(mAdapter);
        listview.setMode(Mode.PULL_FROM_END);
        
        listview.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

                // Do work to refresh the list here.
                        new GetDataTask().execute();
                    }
                });
    }
        
    private List<Map<String, Object>> getData() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
 
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title", "G1");
        map.put("info", "google 1");
        map.put("img", R.drawable.i1);
        list.add(map);
 
        map = new HashMap<String, Object>();
        map.put("title", "G2");
        map.put("info", "google 2");
        map.put("img", R.drawable.i2);
        list.add(map);
 
        map = new HashMap<String, Object>();
        map.put("title", "G3");
        map.put("info", "google 3");
        map.put("img", R.drawable.i3);
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("title", "G4");
        map.put("info", "google 4");
        map.put("img", R.drawable.i3);
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("title", "G5");
        map.put("info", "google 5");
        map.put("img", R.drawable.i3);
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("title", "G6");
        map.put("info", "google 6");
        map.put("img", R.drawable.i3);
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("title", "G7");
        map.put("info", "google 7");
        map.put("img", R.drawable.i3);
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("title", "G8");
        map.put("info", "google 8");
        map.put("img", R.drawable.i3);
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("title", "G9");
        map.put("info", "google 9");
        map.put("img", R.drawable.i3);
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("title", "G10");
        map.put("info", "google 10");
        map.put("img", R.drawable.i3);
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("title", "G11");
        map.put("info", "google 11");
        map.put("img", R.drawable.i3);
        list.add(map);
         
        return list;
    }
    
    
    private class GetDataTask extends AsyncTask<Void, Void, List<Map<String,Object>>> {
        // 后台处理部分
        @Override
        protected List doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
//            String str="Added after refresh...I add";
//            return str;
            List<Map<String, Object>> mList = new ArrayList<Map<String, Object>>();
            Map<String, Object> mMap = new HashMap<String, Object>();
            
            mMap = new HashMap<String, Object>();
            mMap.put("title", "G111");
            mMap.put("info", "google 111");
            mMap.put("img", R.drawable.i1);
            mList.add(mMap);
            
            mMap = new HashMap<String, Object>();
            mMap.put("title", "G112");
            mMap.put("info", "google 112");
            mMap.put("img", R.drawable.i2);
            mList.add(mMap);
            
            mMap = new HashMap<String, Object>();
            mMap.put("title", "G113");
            mMap.put("info", "google 113");
            mMap.put("img", R.drawable.i3);
            mList.add(mMap);
            
            return mList;
        }

        //这里是对刷新的响应,可以利用addFirst()和addLast()函数将新加的内容加到LISTView中
        //根据AsyncTask的原理,onPostExecute里的result的值就是doInBackground()的返回值
        @Override
        protected void onPostExecute(List result) {
            //在头部增加新添内容
            mData.addAll(result);
            
            //通知程序数据集已经改变,如果不做通知,那么将不会刷新mListItems的集合
            mAdapter.notifyDataSetChanged();
            // Call onRefreshComplete when the list has been refreshed.
            listview.onRefreshComplete();

            super.onPostExecute(result);//这句是必有的,AsyncTask规定的格式
        }
    }
}

ListViewAdapter.java

package com.example.listviewdemo.adapter;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.listviewdemo.R;

public class ListViewAdapter extends BaseAdapter{
     private LayoutInflater mInflater;
     private List<Map<String, Object>> list;
     private ViewHolder holder;
     
    public  ListViewAdapter(Context context,List<Map<String,Object>> list){
        this.mInflater = LayoutInflater.from(context);
        this.list = list;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
         
        if (convertView == null) {
             
            holder=new ViewHolder(); 
             
            convertView = mInflater.inflate(R.layout.list_item, null);
            holder.img = (ImageView)convertView.findViewById(R.id.img);
            holder.title = (TextView)convertView.findViewById(R.id.title);
            holder.info = (TextView)convertView.findViewById(R.id.info);
            convertView.setTag(holder);
             
        }else {
             
            holder = (ViewHolder)convertView.getTag();
        }
        holder.img.setBackgroundResource((Integer)list.get(position).get("img"));
        holder.title.setText((String)list.get(position).get("title"));
        holder.info.setText((String)list.get(position).get("info"));
        return convertView;
    }
    
    public final class ViewHolder{
        public ImageView img;
        public TextView title;
        public TextView info;
    }
}
原文地址:https://www.cnblogs.com/hikigaya-yukino/p/4167531.html