ListView 分页加载网络数据

    xiaoxiao2024-12-28  15

    1.分页加载思路

    (1)判断是否滑动到底部 (2)当滑动到底部,往数据源中添加数据,然后调用adapter.notifyDataSetChanged()方法刷新显示的listView数据。

    2. 下面是糗事百科加载的实例,加载效果如下(为了显示效果我在工作线程中休眠了 3s)

    图1

    图2

    当加载数据的时候显示进度,和文字提示,加载完成后,提示会隐藏掉。

    3.下面贴出代码

    主布局:

    <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.day36_808.fenpage2_listview.MainActivity"> <ListView android:id="@+id/listview_main" android:layout_width="match_parent" android:layout_height="match_parent" /> <!--正在加载数据时显示,其余时候隐藏--> <LinearLayout android:id="@+id/progress_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:gravity="center" android:orientation="horizontal" > <ProgressBar android:id="@+id/pb" style="?android:attr/progressBarStyleSmall" android:layout_width="25sp" android:layout_height="25sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="正在加载...." android:textSize="25sp" android:layout_marginLeft="10dp"/> </LinearLayout> </RelativeLayout>

    ListView 的item布局(普通文本显示)

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/text_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:maxLines="2" android:padding="8dp" android:textColor="#515151" android:ellipsize="end" android:textSize="18sp"/> </LinearLayout>

    Java 代码(因为代码不多我就干脆就在一个类中完成了)

    package com.day36_808.fenpage2_listview; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends Activity { private String url = "http://m2.qiushibaike.com/article/list/suggest?page="; private ListView listView; private View viewById; private int currPage=1; //当前显示页面 private ArrayList<Map<String, String>> totalist; private MyAdapter adapter; private boolean isBottom; //判读是否到达底部 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listview_main); viewById = findViewById(R.id.progress_container); //加载第一页的数据 totalist = new ArrayList<>(); adapter = new MyAdapter(totalist); listView.setAdapter(adapter); new MyAsyncTask().execute(url + currPage); //listView 的滚动监听,当到达底部时自动加载数据 listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int state) { //如果滚动状态停止,并到达底部,使进度条和加载提示显示,并加载数据 if (state==SCROLL_STATE_IDLE&&isBottom){ viewById.setVisibility(View.VISIBLE); currPage=currPage+1; new MyAsyncTask().execute(url+currPage); } } @Override public void onScroll(AbsListView absListView, int i, int i1, int i2) { //判读是否滑动到了底部 isBottom=((i+i1)==i2); } }); } //使用异步任务下载,并刷新数据 //连网下载json, 更新ui(绑定数据到Listview) class MyAsyncTask extends AsyncTask<String, Void, byte[]> { @Override protected byte[] doInBackground(String... params) { try { HttpURLConnection con = (HttpURLConnection) new URL(params[0]).openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(5000); con.connect(); if (con.getResponseCode() == 200) { BufferedInputStream bis = new BufferedInputStream(con.getInputStream()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int i; while((i = bis.read()) != -1) { bos.write(i); bos.flush(); } bis.close(); Log.d("lewis", "doInBackground: " + bos.toString()); SystemClock.sleep(3 * 1000); return bos.toByteArray(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(byte[] result) { super.onPostExecute(result); if (result != null) { try { String json = new String(result, "UTF-8"); List<Map<String, String>> list = parseJSON(json); totalist.addAll(list); adapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(MainActivity.this, "网络异常!", Toast.LENGTH_SHORT).show(); } viewById.setVisibility(View.GONE); } } // json解析方法 private List<Map<String, String>> parseJSON(String json) { List<Map<String, String>> list = new ArrayList<Map<String,String>>(); try { JSONObject jsonObject = new JSONObject(json); JSONArray array_items = jsonObject.getJSONArray("items"); for (int i = 0; i < array_items.length(); i++) { JSONObject object_item = array_items.getJSONObject(i); Map<String, String> itemMap = new HashMap<String, String>(); itemMap.put("content", object_item.getString("content")); list.add(itemMap); } } catch (JSONException e) { e.printStackTrace(); } return list; } // 定义适配器 private class MyAdapter extends BaseAdapter { private List<Map<String,String>> mapList; public MyAdapter(List<Map<String, String>> mapList) { this.mapList = mapList; } @Override public int getCount() { return mapList.size(); } @Override public Object getItem(int i) { return mapList.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int position, View convertView, ViewGroup viewGroup) { ViewHolder holder=null; if (convertView==null){ holder=new ViewHolder(); convertView= LayoutInflater.from(getApplicationContext()) .inflate(R.layout.item_listview,viewGroup,false); holder.text_content= (TextView) convertView.findViewById(R.id.text_content); convertView.setTag(holder); }else { holder= (ViewHolder) convertView.getTag(); } holder.text_content.setText(mapList.get(position).get("content")); return convertView; } class ViewHolder{ TextView text_content; } } }
    转载请注明原文地址: https://ju.6miu.com/read-1295089.html
    最新回复(0)