Android实战简易教程-第二十五枪(基于Baas的数据表查询下拉刷新和上拉载入实现!)

上一节我们实现了数据表的载入,可是,当数据表数据非常多时。我们就要考虑数据的分页。这里我们选用了PullToRefreshListView控件,先看一下该控件的说明:

效果图: 

                               正在刷新                                                                       刷新后

      

一、导入Library

下载源代码后(https://github.com/chrisbanes/Android-PullToRefresh),里面有个Libraryproject,加入project到Eclipse中;

另外extras目录还有两个project:PullToRefreshListFragment和PullToRefreshViewPager,因为我们的这个用不到他们的库文件,所以不必导入了。

二、实战

1、新建project,加入Libray库到project中

新建project(try_PullToRefresh)后,右键-》Properties-》Android-》Add  选择上面的Library,然后就是这个样子的

2、重写activity_main.xml

XML内容为:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.       
  7. <!--     The PullToRefreshListView replaces a standard ListView widget. -->  
  8.     <com.handmark.pulltorefresh.library.PullToRefreshListView  
  9.         android:id="@+id/pull_refresh_list"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="fill_parent"  
  12.         android:cacheColorHint="#00000000"  
  13.         android:divider="#19000000"  
  14.         android:dividerHeight="4dp"  
  15.         android:fadingEdge="none"  
  16.         android:fastScrollEnabled="false"  
  17.         android:footerDividersEnabled="false"  
  18.         android:headerDividersEnabled="false"  
  19.         android:smoothScrollbar="true" />  
  20.   
  21. </LinearLayout>  

当中中间那一大段<com.handmark.pull………………/>就是相当于ListView控件,用这段来取代原是ListView控件的代码

以下我们看一下详细怎么实现的。

先在数据表中插入数据:


然后看代码。MainActivity.java:

package com.bmob.pagingdemo;

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

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class MainActivity extends Activity {

	PullToRefreshListView mPullToRefreshView;
	private ILoadingLayout loadingLayout;
	ListView mMsgListView;
	List<TestData> bankCards = new ArrayList<TestData>();// 数据list

	private static final int STATE_REFRESH = 0;// 下拉刷新
	private static final int STATE_MORE = 1;// 载入很多其它

	private int limit = 10; // 每页的数据是10条
	private int curPage = 0; // 当前页的编号。从0開始

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

		Bmob.initialize(this, "8f3ffb2658d8a3366a70a0b0ca0b71b2");// 初始化
		queryData(0, STATE_REFRESH);

		initListView();// 初始化ListView
	}

	
	private void initListView() {
		mPullToRefreshView = (PullToRefreshListView) findViewById(R.id.list);
		loadingLayout = mPullToRefreshView.getLoadingLayoutProxy();
		loadingLayout.setLastUpdatedLabel("");
		loadingLayout
				.setPullLabel(getString(R.string.pull_to_refresh_bottom_pull));// 下拉标签
		loadingLayout
				.setRefreshingLabel(getString(R.string.pull_to_refresh_bottom_refreshing));// 刷新标签
		loadingLayout
				.setReleaseLabel(getString(R.string.pull_to_refresh_bottom_release));// 释放标签
		// //滑动监听
		mPullToRefreshView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

				if (firstVisibleItem == 0) {
					loadingLayout.setLastUpdatedLabel("");
					loadingLayout
							.setPullLabel(getString(R.string.pull_to_refresh_top_pull));
					loadingLayout
							.setRefreshingLabel(getString(R.string.pull_to_refresh_top_refreshing));
					loadingLayout
							.setReleaseLabel(getString(R.string.pull_to_refresh_top_release));
				} else if (firstVisibleItem + visibleItemCount + 1 == totalItemCount) {// 载入完成
					loadingLayout.setLastUpdatedLabel("");
					loadingLayout
							.setPullLabel(getString(R.string.pull_to_refresh_bottom_pull));
					loadingLayout
							.setRefreshingLabel(getString(R.string.pull_to_refresh_bottom_refreshing));
					loadingLayout
							.setReleaseLabel(getString(R.string.pull_to_refresh_bottom_release));
				}
			}
		});

		// 下拉刷新监听
		mPullToRefreshView
				.setOnRefreshListener(new OnRefreshListener2<ListView>() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						// 下拉刷新(从第一页開始装载数据)
						queryData(0, STATE_REFRESH);
					}

					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						// 上拉载入很多其它(载入下一页数据)
						queryData(curPage, STATE_MORE);
					}
				});

		mMsgListView = mPullToRefreshView.getRefreshableView();
		// 再设置adapter
		mMsgListView.setAdapter(new DeviceListAdapter(this));
	}

	/**
	 * 分页获取数据
	 * 
	 * @param page
	 *            页码
	 * @param actionType
	 *            ListView的操作类型(下拉刷新、上拉载入很多其它)
	 */
	private void queryData(final int page, final int actionType) {
		Log.i("bmob", "pageN:" + page + " limit:" + limit + " actionType:"
				+ actionType);

		BmobQuery<TestData> query = new BmobQuery<TestData>();
		query.setLimit(limit); // 设置每页多少条数据
		query.setSkip(page * limit); // 从第几条数据開始,
		query.findObjects(this, new FindListener<TestData>() {

			@Override
			public void onSuccess(List<TestData> arg0) {
				// TODO Auto-generated method stub

				if (arg0.size() > 0) {//能载入到数据
					if (actionType == STATE_REFRESH) {
						// 当是下拉刷新操作时,将当前页的编号重置为0。并把bankCards清空,又一次加入
						curPage = 0;
						bankCards.clear();
					}

					// 将本次查询的数据加入到bankCards中
					for (TestData td : arg0) {
						bankCards.add(td);
					}

					// 这里在每次载入完数据后。将当前页码+1。这样在上拉刷新的onPullUpToRefresh方法中就不须要操作curPage了
					curPage++;
					showToast("第" + (page + 1) + "页数据载入完成");
				} else if (actionType == STATE_MORE) {//数据载入完成
					showToast("没有很多其它数据了");
				} else if (actionType == STATE_REFRESH) {//无数据
					showToast("没有数据");
				}
				mPullToRefreshView.onRefreshComplete();
			}

			@Override
			public void onError(int arg0, String arg1) {
				// TODO Auto-generated method stub
				showToast("查询失败:" + arg1);
				mPullToRefreshView.onRefreshComplete();
			}
		});
	}

	/**
	 * Adapter
	 * 
	 * @author Administrator
	 * 
	 */
	private class DeviceListAdapter extends BaseAdapter {

		Context context;

		public DeviceListAdapter(Context context) {
			this.context = context;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {

				convertView = LayoutInflater.from(context).inflate(
						R.layout.list_item_bankcard, null);
				holder = new ViewHolder();
				holder.tv_cardNumber = (TextView) convertView
						.findViewById(R.id.tv_cardNumber);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			TestData td = (TestData) getItem(position);

			holder.tv_cardNumber.setText(td.getName());
			return convertView;
		}

		class ViewHolder {
			TextView tv_cardNumber;
		}

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

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

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

	}

	private void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

}

TestData.java:

package com.bmob.pagingdemo;

import cn.bmob.v3.BmobObject;

public class TestData extends BmobObject {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}
main.xml:

<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"
    android:orientation="vertical" >

    <com.handmark.pulltorefresh.library.PullToRefreshListView
        xmlns:ptr="http://schemas.android.com/apk/res/com.bmob.pagingdemo"
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fadingEdge="none"
        android:fastScrollEnabled="false"
        android:smoothScrollbar="true"
        ptr:ptrMode="both" />

</LinearLayout>

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bmob.pagingdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="14" />

    <uses-permission android:name="android.permission.INTERNET" /> <!-- 同意应用打开网络套接口 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


执行实例。下拉刷新:


上拉载入,每次载入10条数据:


本实例有个问题,初次进入时不能载入数据。必须下拉才干载入数据,请能找出问题的朋友联系我:291214603。多谢。

喜欢的朋友能够关注我。谢谢!


原文地址:https://www.cnblogs.com/gccbuaa/p/6961564.html