自动加载下一页

社会化APP(比如凤凰FM)在列表类页面中,当用户滑动到当前页面的最后一条数据后,会自动下载下一页数据。今天在这里做一个Demo探究一下。

理论讲解

  1. 定义一个加载更多的接口
package com.example.androidtest;

/** */
public interface LoadListDataInterface {
/** * * @param position getView */
    public void loadMoreData();

}
  1. 在Activity中实现该接口
package com.example.androidtest;


public class MainActivity extends Activity implements LoadListDataInterface {

    @Override
    public void loadMoreData() {
        //TODO
        }

}
  1. 将该接口放入Adapter中,借用Adapter.getView判断用户是否滑动到了最后一条数据
    public LoadNextAdapter(Context context, LoadListDataInterface dataInferface) {
        this.mContext = context;
        mLoadDataInferface = dataInferface;
        }
        @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (mLoadDataInferface != null && position == getCount() - 1) {
            mLoadDataInferface.loadMoreData();
        }
    public void appendData(List<AnchorBean> anchorList) {
        if (mData == null) {
            mData = new ArrayList<AnchorBean>();
        }
        if (anchorList != null && anchorList.size() > 0) {
            mData.addAll(anchorList);
            // be careful,notifyDataSetChanged must be called when there is more
            // data
            // or there will be a loop request
            notifyDataSetChanged();
        }
    }

这里要注意以下,获取下一页数据的时候,只有“真”的获取到了数据在调用notifyDataSetChanged(),否则会陷入死循环。

到这里就结束了。

2.张贴详细代码

由于网络访问/网络数据的解析等较为繁琐,这里使用了Volley+Gson完成。

  • Model
package com.example.androidtest.model;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;

/** * 用于解析从服务器返回的数据 * * @author Chuanhang.Gu * */
public class ResponseBean {
    @SerializedName("ErrorCode")
    private String errorCode;
    @SerializedName("ErrorString")
    private String errorString;
    /** * 当返回的数据合法时,才有意义 */
    @SerializedName("ResponseObject")
    private JsonObject responseObject;

    @Override
    public String toString() {
        return "ErrorCode:" + errorCode + " ErrorString:" + errorString
                + " ResponseObject" + responseObject;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorString() {
        return errorString;
    }

    public void setErrorString(String errorString) {
        this.errorString = errorString;
    }

    public JsonObject getResponseObject() {
        return responseObject;
    }

    public void setResponseObject(JsonObject responseObject) {
        this.responseObject = responseObject;
    }

}
package com.example.androidtest.model;

import java.io.Serializable;

/** * @author Chuanhang.Gu * */
public class AnchorBean implements Serializable{
    public static final String tableName = "UserTable";
    private static final long serialVersionUID = 1L;
    private String UserName;

    public String getUserName() {
        return UserName;
    }
    public void setUserName(String userName) {
        UserName = userName;
    }
}
  • LoadNextAdapter.java
    -
    用到的布局文件item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/usernameTextView" android:layout_width="match_parent" android:layout_height="100dp" android:gravity="center" android:textColor="@color/black" android:textStyle="bold" />
package com.example.androidtest;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.androidtest.model.AnchorBean;

public class LoadNextAdapter extends BaseAdapter {

    private LoadListDataInterface mLoadDataInferface;
    private List<AnchorBean> mData;
    private Context mContext;
    private LayoutInflater inflater;

    public LoadNextAdapter(Context context, LoadListDataInterface dataInferface) {
        this.mContext = context;
        mLoadDataInferface = dataInferface;
        inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public List<AnchorBean> getData() {
        return mData;
    }

    public void setData(List<AnchorBean> anchorList) {
        mData = anchorList;
        notifyDataSetChanged();
    }

    public void appendData(List<AnchorBean> anchorList) {
        if (mData == null) {
            mData = new ArrayList<AnchorBean>();
        }
        if (anchorList != null && anchorList.size() > 0) {
            mData.addAll(anchorList);
            // be careful,notifyDataSetChanged must be called when there is more
            // data
            // or there will be a loop request
            notifyDataSetChanged();
        }
    }

    @Override
    public AnchorBean getItem(int position) {
        return mData == null ? null : mData.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (mLoadDataInferface != null && position == getCount() - 1) {
            mLoadDataInferface.loadMoreData();
        }
        View v = convertView;
        ViewHolder viewHolder;
        if (v == null) {
            v = inflater.inflate(R.layout.item, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.userNameTextView = (TextView) v
                    .findViewById(R.id.usernameTextView);
            v.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) v.getTag();
        }

        AnchorBean anchorBean = getItem(position);
        viewHolder.userNameTextView.setText(anchorBean.getUserName());
        return v;
    }

    @Override
    public int getCount() {
        return mData == null ? 0 : mData.size();
    }

    static class ViewHolder {
        TextView userNameTextView;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

}
  • MainActivity
package com.example.androidtest;

import java.util.List;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.example.androidtest.model.AnchorBean;
import com.example.androidtest.model.ResponseBean;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class MainActivity extends Activity implements LoadListDataInterface {
    public static final String BASE_URL = "http://www.dingdongfm.com/DingDongFM/servlet/MobileServlet";
    public static final String TAG = MainActivity.class.getSimpleName();
    protected LoadNextAdapter mAdapter;
    private ListView mListView;
    public static final int ITEM_PAGE = 7;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mListView = new ListView(this);
        setContentView(mListView);
        mAdapter = new LoadNextAdapter(this, this);
        mListView.setAdapter(mAdapter);
        loadMoreData();
    }
    @Override
    public void loadMoreData() {
        Uri.Builder uriBuilder = Uri
                .parse(BASE_URL)
                .buildUpon()
                .appendQueryParameter("ObjectName", "UserTable")
                .appendQueryParameter("Style", "Total")
                .appendQueryParameter("StartRow", "" + mAdapter.getCount())
                .appendQueryParameter("EndRow",
                        "" + (mAdapter.getCount() + ITEM_PAGE))
                .appendQueryParameter("model", "" + 28);
        GsonRequest<ResponseBean> gsonRequest = new GsonRequest<ResponseBean>(
                uriBuilder.build().toString(), ResponseBean.class, null,
                mSuccessListener, errorListener);
        gsonRequest.setShouldCache(false);
        RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);
        mQueue.add(gsonRequest);

    }

    ErrorListener errorListener = new ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            // TODO Auto-generated method stub

        }
    };

    Listener<ResponseBean> mSuccessListener = new Listener<ResponseBean>() {

        @Override
        public void onResponse(ResponseBean responseBean) {
            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();
            List<AnchorBean> anchorList = null;
            try {
                anchorList = gson.fromJson(responseBean.getResponseObject()
                        .getAsJsonArray("UserTable"),
                        new TypeToken<List<AnchorBean>>() {
                        }.getType());
                if (mAdapter.getCount() == 0) {
                    mAdapter.setData(anchorList);
                } else if (mAdapter.getCount() > 0) {
                    mAdapter.appendData(anchorList);
                } else if (anchorList.size() == 0) {
                    Toast.makeText(MainActivity.this, " no more data ~",
                            Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

}

Demo下载:
http://download.csdn.net/detail/guchuanhang/9507965

你可能感兴趣的:(用户体验)