PullToRefreshListView进阶(二)----->上拉加载

效果图:转自harvic当乌龟有了梦想……

正在刷新                                                                                                  刷新后

      

assets文件夹里面

[{"name":"林珊","info":"上传了一张新照片油画”","photo":"youhua"},
{"name":"叶亚楠","info":"上传了一张新照片日系妆”","photo":"rixizhuang"},
{"name":"王颖","info":"上传了一张新照片最爱”","photo":"zuiai"},
{"name":"罗智宜","info":"上传了一张新照片猫猫”","photo":"maomao"},
{"name":"罗智宜","info":"上传了一张新照片鱼”","photo":"yu"},
{"name":"罗智宜","info":"上传了一张新照片卖萌”","photo":"maimeng"},
{"name":"程璐春","info":"上传了一张新照片西藏”","photo":"xizang"},
{"name":"谢以荷","info":"上传了一张新照片海边”","photo":"haibian"}]


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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>

item.xml(每个item的布局)

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

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5px" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FFFFFF00"
            android:textSize="22px" />

        <TextView
            android:id="@+id/info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FF00FFFF"
            android:textSize="13px" />
    </LinearLayout>

</LinearLayout>

MainActivity

package com.example.try_pulltorefresh_map;

/**
 * 完成了从TXT文本中提取,并向下刷新
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ListActivity {

	private ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
	private PullToRefreshListView mPullRefreshListView;
	MyAdapter adapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 获取控件listview
		mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);

		// 设定上拉监听函数
		mPullRefreshListView
				.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);

						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);

						// 开始异步任务加载新数据
						new GetDataTask().execute();
					}
				});

		// 设置底部下拉刷新模式
		mPullRefreshListView.setMode(Mode.PULL_FROM_END);

		// 1、获取LIST数据
		listItem = getData();
		// 2、获取适配器
		adapter = new MyAdapter(this);
		// 3、设置适配器
		ListView actualListView = mPullRefreshListView.getRefreshableView();
		actualListView.setAdapter(adapter);

	}

	private class GetDataTask extends
			AsyncTask<Void, Void, HashMap<String, Object>> {

		// 后台处理部分
		@Override
		protected HashMap<String, Object> doInBackground(Void... params) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			HashMap<String, Object> map = new HashMap<String, Object>();
			try {

				map = new HashMap<String, Object>();
				map.put("name", "林珊");
				map.put("info", "上传了一张新照片油画");
				map.put("img", "youhua");

			} catch (Exception e) {
				setTitle("map出错了");
				return null;
			}

			return map;
		}

		/**
		 * 这里是对刷新的响应,可以利用addFirst()和addLast()函数将新加的内容加到LISTView中
		 * 根据AsyncTask的原理,onPostExecute里的result的值就是doInBackground()的返回值
		 */
		@Override
		protected void onPostExecute(HashMap<String, Object> result) {
			// 在头部增加新添内容
			try {
				listItem.add(result);

				// 通知程序数据集已经改变,如果不做通知,那么将不会刷新mListItems的集合
				adapter.notifyDataSetChanged();
				mPullRefreshListView.onRefreshComplete();
			} catch (Exception e) {
				setTitle(e.getMessage());
			}

			super.onPostExecute(result);
		}
	}

	/**
	 * listview界面初始化的数据data 每一个item就是一个hashMap集合 一页数据就是一个存放map的ArrayList集合
	 * 
	 */
	private ArrayList<HashMap<String, Object>> getData() {
		ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		InputStream inputStream;
		try {
			// 获取一个输入流
			inputStream = this.getAssets().open("my_home_friends.txt");
			String json = readTextFile(inputStream);
			// 创建JSONArray对象--json格式的json字符串
			JSONArray array = new JSONArray(json);

			for (int i = 0; i < array.length(); i++) {
				map = new HashMap<String, Object>();
				map.put("name", array.getJSONObject(i).getString("name"));
				map.put("info", array.getJSONObject(i).getString("info"));
				map.put("img", array.getJSONObject(i).getString("photo"));
				list.add(map);
			}
			return list;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}

	/**
	 * 从assets文件中读取一串JSon字符串,生成json字符串对象
	 */
	public String readTextFile(InputStream inputStream) {
		String readedStr = "";
		BufferedReader br;
		try {
			// 字符读取流
			br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String tmp;
			while ((tmp = br.readLine()) != null) {
				readedStr += tmp;
			}
			br.close();
			inputStream.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return readedStr;
	}

	public final class ViewHolder {
		public ImageView img;
		public TextView name;
		public TextView info;
	}

	/**
	 * 适配器类
	 * 
	 */
	public class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

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

		@Override
		public Object getItem(int arg0) {
			return listItem.get(arg0);
		}

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

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder = null;
			if (convertView == null) {

				holder = new ViewHolder();

				convertView = mInflater.inflate(R.layout.item, null);
				holder.img = (ImageView) convertView.findViewById(R.id.img);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.info = (TextView) convertView.findViewById(R.id.info);
				convertView.setTag(holder);

			} else {

				holder = (ViewHolder) convertView.getTag();
			}

			holder.img.setImageBitmap(getHome((String) listItem.get(position)
					.get("img")));
			holder.name.setText((String) listItem.get(position).get("name"));
			holder.info.setText((String) listItem.get(position).get("info"));

			return convertView;
		}

	}

	/**
	 * 根据图片名称获取主页图片
	 */
	public Bitmap getHome(String photo) {
		String homeName = photo + ".jpg";
		InputStream is = null;

		try {
			is = getAssets().open("home/" + homeName);
			Bitmap bitmap = BitmapFactory.decodeStream(is);
			is.close();
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值