ListView下拉加载二(分页)

这次在一的基础上做了数据通过HttpClient远程获取显示 并且分页,首先看下效果吧:

以上就是效果图了 下面看下具体代码实现吧

主要代码和上节差不多

主入口代码:

package com.tp.soft.app;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.tp.soft.entity.Article;
import com.tp.soft.http.HttpUtil;
import com.tp.soft.io.IOUtil;
import com.tp.soft.util.Constant;

public class MainActivity extends Activity implements OnScrollListener, OnItemClickListener{

    private ListView mListView;

    private View mLoadMoreView;

    private ProgressBar mLoadBtn;

    private PageAdapter adapter;

    private Handler handler = new Handler();

    private int curPage;

    private int visibleItemCount;       // 当前窗口可见项总数  

    private int visibleLastIndex = 0;   //最后的可视项索引   

    private long total;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLoadMoreView = getLayoutInflater().inflate(R.layout.loadmore, null);
        mLoadBtn = (ProgressBar) mLoadMoreView.findViewById(R.id.progressBar1);
        //mLoadBtn.setOnClickListener(this);

        mListView = (ListView) findViewById(R.id.menuList);

        mListView.addFooterView(mLoadMoreView);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("curPage", 1);
        params.put("limit", 10);
        List<Article> articleList = getArticleList(params);
        adapter = new PageAdapter(articleList);
        mListView.setAdapter(adapter);

        //下拉滚动触发事件
        mListView.setOnScrollListener(this);
        mListView.setOnItemClickListener(this);
    }

    private List<Article> getArticleList(Map<String, Object> params) {
        HttpResponse response = HttpUtil.getHttpResponse(Constant.FINDARTICLE, params, Constant.ENCODING);
        List<Article> articles = new ArrayList<Article>();
        if(response!=null){
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                try{
                    IOUtil ioUtil = new IOUtil();
                    String resultJson = ioUtil.getJson(response.getEntity().getContent());
                    JSONObject jsonObject = new JSONObject(resultJson);
                    curPage = jsonObject.getInt("curPage");
                    total = jsonObject.getLong("total");
                    JSONArray jsonArray = jsonObject.getJSONArray("rows");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject obj = jsonArray.getJSONObject(i);
                        int id = obj.getInt("a_id");
                        String title = obj.getString("title");
                        String content = obj.getString("content");
                        Timestamp creat_time = new Timestamp(obj.getLong("create_time"));
                        Article article = new Article();
                        article.setA_id(id);
                        article.setTitle(title);
                        article.setContent(content);
                        article.setCreate_time(creat_time);
                        articles.add(article);
                    }
                }catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return articles;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /*@Override
    public void onClick(View v) {
        mLoadBtn.setText("正在加载中...");
        MyRunnable r = new MyRunnable();
        handler.postDelayed(r, 2000);
    }*/

    class MyRunnable implements Runnable{
        @Override
        public void run() {
            Log.e("visibleLastIndex", visibleLastIndex+"");
            if(visibleLastIndex== total + 1){
                mListView.removeFooterView(mLoadMoreView);
                adapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this, "数据全部加载完成", Toast.LENGTH_SHORT).show();
            }else{
                loadMoreDate();
            }

            //更新UI
            adapter.notifyDataSetChanged();
            //mLoadBtn.setText("查看更多...");
        }
    }

    class PageAdapter extends BaseAdapter {

        List<Article> itemList;

        public PageAdapter(List<Article> itemList){
            this.itemList = itemList;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.menu, null);
            }
            TextView titleView = (TextView) convertView.findViewById(R.id.showView);
            TextView contentView = (TextView) convertView.findViewById(R.id.content);
            titleView.setText(itemList.get(position).getTitle());
            contentView.setText(itemList.get(position).getContent());

            return convertView;
        }

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

        @Override
        public Object getItem(int position) {
            return itemList.get(position);
        }

        @Override
        public int getCount() {
            return itemList.size();
        }

        public void addItem(Article article){
            itemList.add(article);
        }
    }

    private void loadMoreDate() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("curPage", curPage + 1);
        params.put("limit", 10);
        List<Article> articleList = getArticleList(params);
        for (Article article : articleList) {
            adapter.addItem(article);
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        visibleLastIndex = totalItemCount;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        //不滚动
        if(scrollState == OnScrollListener.SCROLL_STATE_IDLE){
            //滚动最底部
            if(view.getLastVisiblePosition() == view.getCount() -1){
                //mLoadBtn.setText("正在加载中...");
                MyRunnable r = new MyRunnable();
                handler.postDelayed(r, 2000);
            }
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
        ListView listView = (ListView) parent;
        Article article = (Article) listView.getItemAtPosition(position);
        Intent intent = new Intent(MainActivity.this, ArticleDetalActivity.class);
        intent.putExtra("article", article);
        startActivity(intent);
    }

}

文章详细信息显示ArticleDetalActivity代码:

package com.tp.soft.app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

import com.tp.soft.entity.Article;
import com.tp.soft.util.DateUtil;

public class ArticleDetalActivity extends Activity implements OnClickListener{

    private Handler handler = new Handler();

    private TextView mTitle;
    private TextView mContent;
    private TextView mTime;

    private ImageButton mBackBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_detal);

        mTitle = (TextView) findViewById(R.id.d_title);
        mContent = (TextView) findViewById(R.id.d_content);
        mTime = (TextView) findViewById(R.id.d_time);

        mBackBtn = (ImageButton) findViewById(R.id.backBtn);

        Intent intent = getIntent();
        Article article = (Article) intent.getSerializableExtra("article");
        mTitle.setText(article.getTitle());
        mContent.setText(article.getContent());
        mTime.setText("发表日期:"+DateUtil.timestampToStr(article.getCreate_time(), "yyyy-MM-dd HH:mm:ss"));

        mBackBtn.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.article_detal, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        ArticleDetalActivity.this.setResult(RESULT_OK, getIntent());
        ArticleDetalActivity.this.finish();
    }
}

HttpUtil封装:

package com.tp.soft.http;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

public class HttpUtil {
    public static HttpResponse getHttpResponse(String serverPath, Map<String, Object> params, String encoding){
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        if(null != params && !params.isEmpty()){
            for(Map.Entry<String, Object> entry : params.entrySet()){
                pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }

        HttpResponse response = null;
        try {
            HttpPost post = new HttpPost(serverPath);
            post.setEntity(new UrlEncodedFormEntity(pairs, encoding));
            response = getHttpClient().execute(post);
        }catch (ConnectTimeoutException e) {
            Log.e("提示", "连接超时");
            return null;
        } catch (SocketTimeoutException e) {
            Log.e("提示", "Socket连接超时");
            return null;
        } catch (Exception e) {
            Log.e("提示", e.getLocalizedMessage());
            return null;
        }
        return response;
    }

    public static synchronized HttpClient getHttpClient(){
        HttpParams params = new BasicHttpParams();
        ConnManagerParams.setTimeout(params, 3000);
        HttpConnectionParams.setConnectionTimeout(params, 3000);
        HttpConnectionParams.setSoTimeout(params, 3000);

        // 设置我们的HttpClient支持HTTP和HTTPS两种模式
        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        // 使用线程安全的连接管理来创建HttpClient
        ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
        HttpClient client = new DefaultHttpClient(conMgr ,params);
        return client;
    }
}

服务器代码:

@POST
    @Path(value="/findArticle")
    @Produces(MediaType.APPLICATION_JSON)
    @Override
    public Result findArticleAll(@FormParam(value="curPage") String curPage, @FormParam(value="limit") String limit)throws BaseServiceException {
        Result result = new Result();
        List<Article> aList = new ArrayList<Article>();
        Article article = new Article();
        article.setPageable(true);
        article.setStart((Integer.parseInt(curPage) - 1) * Integer.parseInt(limit));
        article.setLimit(Integer.parseInt(limit));
        try{
            aList = articleDao.find(article);
        }catch (DataAccessException e) {
            LOG.error("【ibatis】查询文章列表失败", e);
            throw new BaseServiceException(e.getLocalizedMessage());
        }

        long total = 0;
        try{
            total = articleDao.getTotal(article);
        }catch (DataAccessException e) {
            LOG.error("【ibatis】查询文章总数失败", e);
            throw new BaseServiceException(e.getLocalizedMessage());
        }
        result.setRows(aList);
        result.setCurPage(Integer.parseInt(curPage));
        result.setTotal(total);
        return result;
    }

核心代码就这么多了 界面代码就不一一贴出了

想要具体代码可以到http://download.csdn.net/detail/taopeng_100/7864393地址下载

时间: 2024-10-15 10:45:44

ListView下拉加载二(分页)的相关文章

ListView下拉加载一(分页)

首先创建在主xml里放置一个listview列表,代码如下: <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_par

Windows Phone 8.1开发:如何让ListView下拉加载更多?

Windows Phone 8.1开发中使用ListView作为数据呈现载体时,经常需要一个下拉(拇指向上滑动)加载更多的交互操作.如何完成这一操作呢?下面为您阐述. 思路是这样的: 1.在ListView的loaded事件中,获取ListView中的ScrollView对象. 如何获得ScrollViewer,这篇文章说的很清楚! Windows Phone 8.1开发:如何从ListView中,获取ScrollViewer对象 2. 给ScrollViewer创建事件,上篇文章也说了. 3.

WP &amp; Win10开发:实现ListView下拉加载的两种方法

1.通过ListView控件的ContainerContentChanging方法.该方法在列表项被实例化时触发,在列表项最后一个项目实例化的时候触发刷新数据逻辑就可以实现下拉加载了. 代码如下://list_ContainerContentChanging在列表项被实例化是触发. private void list_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args) { if

ListView上拉加载下拉刷新

主要用到了这个几个文件,MainActivity是界面的Activity,MyAdapter是ListView的自定义适配,MyListView是自定义带头部LIistView,如果只需要上拉加载就不需要:activity_main.xml是住界面,item.xml是ListView的子布局里面只有一个TextView,listview_footer.xml是listview的加载更多的底部布局,listview_header.xml是listview的头部布局. MainActivity.ja

Android中listView的下拉加载功能实现

今天给大家讲讲android开发中比较常见的listView的下拉加载,其实也可以叫做分页加载.为什么会有这个叫法呢?说说我的理解吧! 从字面上很好理解.当你滑动一个列表到底部的时候,这个时候就会出现正在加载的底部加载布局去加载更多的数据.这里拿微信作为一个例子,如下图所示: 如上图所示红色方框的部分就是底部的加载布局.从一定程度上这样做是必要的,为了优化用户的体验.你可以想想,假如你点开微信的朋友圈的时候,如果没有做分页加载,那么你需要等待很久的时间才能够看到你和朋友发的一些状态.这是因为这个

ListView上拉加载和下拉刷新多种实现方式

ListView上拉加载和下拉刷新多种实现方式 该篇为ListView下拉刷新和上拉加载实现的各种方法大合集.可能在具体的细节逻辑上处理不太到位,但基本上完成逻辑的实现.细节方面,个人可以根据自己的需求进行完善. 该博客将以四种思路来完成下拉刷新和上拉加载 自定义View实现上拉加载和下拉刷新 使用PullToRefresh 实现上拉加载和下拉刷新 使用Ultra-Pull-To-Refresh实现上拉加载和下拉刷新 使用SwipeToRefreshLayout实现上拉加载和下拉刷新 如果你对L

android自定义控件之ListView上拉加载与下拉刷新

自定义控件LoadLayout import android.content.Context; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import andr

Android MVP设计框架模板 之 漂亮ListView上拉刷新下拉加载更多

mvp的全称为Model-View-Presenter,Model提供数据,View负责显示,Controller/Presenter负责逻辑的处理.MVP与MVC有着一个重大的区别:在MVP中View并不直接使用Model,它们之间的通信是通过Presenter (MVC中的Controller)来进行的,所有的交互都发生在Presenter内部,而在MVC中View会直接从Model中读取数据而不是通过 Controller. 项目中大部分是面对接口编程,通过P层可以预先将所有需要的接口功能

listview上拉加载上一页 下拉加载下一页共通处理

先什么都不说了,上效果图: 第一页默认显示: 上拉加载下一页: 拉至一定高度: 松开 加载中: 下拉加载上一页: 下拉至一定高度: 松开 加载中: 代码已经上传:http://download.csdn.net/detail/zengchao2013/8837971 共通的header和footer可以直接使用. 需要传入的三个参数:是否是第一页,是否是最后一页,当前页数 用于header和footer的UI显示,第一页header隐藏,最后一页footer隐藏.