activity:
<LinearLayout 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.zhangli.xiala.MainActivity" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
myview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textView"
android:layout_gravity="center"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
UrlDemo:
存放网络加载数据的一个类:
package com.zhangli.xiala;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlDemo {
public static byte[] loadRawDataFromURL(String u) throws Exception {
URL url = new URL(u);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final int BUFFER_SIZE = 2048;
final int EOF = -1;
int c;
byte[] buf = new byte[BUFFER_SIZE];
while (true) {
c = bis.read(buf);
if (c == EOF)
break;
baos.write(buf, 0, c);
}
conn.disconnect();
is.close();
byte[] data = baos.toByteArray();
baos.flush();
return data;
}
}
MainActivity:
package com.zhangli.xiala;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
// 数据源
private ArrayList<HashMap<String, Object>> data;
private String IMAGE_KEY = "image", TEXT_KEY = "text";
private ArrayAdapter adapter;
private ListView listView;
private Activity activity;
private String URL_IMAGE = "http://avatar.csdn.net/F/E/F/1_zhangli_.jpg";
private String CACHE_URL_KEY = "cache_url_key", CACHE_BITMAP = "cache_bitmap";
private ArrayList<HashMap<String, Object>> cache;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
Resources res = getResources();
data = new ArrayList<HashMap<String, Object>>();
cache = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < 20; i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(IMAGE_KEY, BitmapFactory.decodeResource(res, R.drawable.ic_launcher));
map.put(TEXT_KEY, i);
data.add(map);
}
listView = (ListView) findViewById(R.id.listView);
adapter = new MyAdapter(this, -1);
listView.setAdapter(adapter);
listView.setOnScrollListener(new OnScrollListener() {
private int firstVisibleItem, visibleItemCount, totalItemCount;
/**
* firstVisibleItem:第一条数据 visibleItemCount:屏幕显示的数据数量
* totalItemCount:总的数据数量
*/
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// isTop:true表示ListView完全見頂部。isBottom:true,listview完全見底。
boolean isTop = false, isBottom = false;
if ((visibleItemCount > 0) && (firstVisibleItem == 0)) {
if (view.getChildAt(0).getTop() >= 0) {
isTop = true;
}
} else if ((totalItemCount > 0) && (view.getLastVisiblePosition() == totalItemCount - 1)) {
if (view.getBottom() == view.getChildAt(view.getChildCount() - 1).getBottom()) {
isBottom = true;
}
}
// SCROLL_STATE_IDLE表示刷新完成
boolean b = false;
if (firstVisibleItem == totalItemCount - visibleItemCount) {
b = true;
}
;
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
if (firstVisibleItem == 0 && isTop) {
new AddTopAsyncTask().execute(URL_IMAGE);
} else if (isBottom && b) {
new AddBottomAsyncTask().execute(URL_IMAGE);
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.firstVisibleItem = firstVisibleItem;
this.visibleItemCount = visibleItemCount;
this.totalItemCount = totalItemCount;
}
});
}
private void loadNewDate(String url) {
// 检查缓存
for (int i = 0; i < cache.size(); i++) {
HashMap<String, Object> map = cache.get(i);
String u = map.get(CACHE_URL_KEY) + "";
if (u.equals(url)) {
// 发现有相同的缓存,直接取出来加载
Bitmap bmp = (Bitmap) map.get(CACHE_BITMAP);
Topadd(bmp);
return;
}
}
// 没有法相相同的缓存,开启线程下载
new AddTopAsyncTask();
}
private class MyAdapter extends ArrayAdapter {
private LayoutInflater mLayoutInflater;
public MyAdapter(Context context, int resource) {
super(context, resource);
mLayoutInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = mLayoutInflater.inflate(R.layout.myview, null);
ImageView image = (ImageView) convertView.findViewById(R.id.imageView);
TextView text = (TextView) convertView.findViewById(R.id.textView);
HashMap<String, Object> map = getItem(position);
image.setImageBitmap((Bitmap) (map.get(IMAGE_KEY)));
text.setText(map.get(TEXT_KEY) + "");
return convertView;
}
@Override
public HashMap<String, Object> getItem(int position) {
return data.get(position);
}
@Override
public int getCount() {
return data.size();
}
}
// 下拉刷新
private class AddTopAsyncTask extends AsyncTask<String, Integer, Bitmap> {
private ProgressDialog pd;
@Override
protected void onPreExecute() {
pd = new ProgressDialog(activity);
pd.setMessage("请稍候,正在下拉刷新加载头部数据。。。");
// 设置样式:进度条显示样式
pd.setProgressStyle(pd.STYLE_HORIZONTAL);
pd.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
int value = values[0];
pd.setProgress(value);
}
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
for (int i = 0; i < 100; i++) {
// 调用上面的onProgressUpdate方法 实现不断增长进度条
publishProgress(i);
try {
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
byte[] bytes = UrlDemo.loadRawDataFromURL(url);
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
// 将加载的数据添加到缓存队列中
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(CACHE_URL_KEY, url);
map.put(CACHE_BITMAP, bmp);
cache.add(map);
return bmp;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
pd.dismiss();
Topadd(result);
}
}
// 上拉刷新
private class AddBottomAsyncTask extends AsyncTask<String, Integer, Bitmap> {
private ProgressDialog pd;
@Override
protected void onPreExecute() {
pd = new ProgressDialog(activity);
pd.setMessage("请稍候,正在上拉刷新加载头部数据。。。");
// 设置样式:进度条显示样式
pd.setProgressStyle(pd.STYLE_HORIZONTAL);
pd.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
int value = values[0];
pd.setProgress(value);
}
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
for (int i = 0; i < 100; i++) {
// 调用上面的onProgressUpdate方法 实现不断增长进度条
publishProgress(i);
try {
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
byte[] bytes = UrlDemo.loadRawDataFromURL(url);
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
// 将加载的数据添加到缓存队列中
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(CACHE_URL_KEY, url);
map.put(CACHE_BITMAP, bmp);
cache.add(map);
return bmp;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
pd.dismiss();
bottomadd(result);
}
}
public void Topadd(Bitmap obj) {
// Bitmap bmp = (Bitmap) obj;
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(IMAGE_KEY, obj);
map.put(TEXT_KEY, data.size());
data.add(0, map);
adapter.notifyDataSetChanged();
}
public void bottomadd(Bitmap obj) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(IMAGE_KEY, obj);
map.put(TEXT_KEY, data.size());
data.add(map);
adapter.notifyDataSetChanged();
// 信息保持在最底部
listView.setSelection(ListView.FOCUS_DOWN);
}
}
上一篇:上拉下拉刷新(1)地址:http://blog.csdn.net/zhangli_/article/details/50318713