在android的开发中,似乎只要涉及到信息列表都会使用到下拉刷新和下拉加载。可见尤其的重要。一般情况下,我们可以选择第三方库来实现。接下来我们就按部就班来实现我们的这个上拉加载和下拉刷新的功能:
第一步:准备开发环境
第三方库:链接地址:http://pan.baidu.com/s/1c0Uvs1E 密码:ujcc
导入第三方库,将第三方的library,并将其与本运用的app依赖,然后同步即可
第二步:主布局文件
<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.qf.myjoke.MainActivity">
<com.handmark.pulltorefresh.library.PullToRefreshListView
xmlns:ptr="http://schemas.android.com/apk/res-auto"
ptr:ptrDrawable = "@drawable/default_ptr_flip"
ptr:ptrAnimationStyle="flip"
ptr:ptrHeaderBackground="#383838"
ptr:ptrHeaderTextColor="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lsItems"
></com.handmark.pulltorefresh.library.PullToRefreshListView>
</RelativeLayout>
第三步:准备显示条目信息的布局
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tvItem"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</TextView>
第四步:添加条目的适配器
/**
*这里很简单,和平时的adapter一样
*/
第五步:设置适配器
PullToRefreshListView listView = (PullToRefreshListView) findViewById(R.id.lsItems);
LayoutItemAdapter adapter = new LayoutItemAdapter(MainActivity.this,jokeList);
listView.setAdapter(adapter);
第六步:设置列表下拉上拉
private void setListView() {
listView.setMode(PullToRefreshBase.Mode.BOTH);//设置既可以下拉也可以上拉
ILoadingLayout headLayout = listView.getLoadingLayoutProxy(true, false);
headLayout.setPullLabel("下来刷新");
headLayout.setRefreshingLabel("刷新中...");
headLayout.setReleaseLabel("放开刷新");
ILoadingLayout footLayout = listView.getLoadingLayoutProxy(false, true);
footLayout.setPullLabel("上拉加载");
footLayout.setRefreshingLabel("加载中...");
footLayout.setReleaseLabel("放开加载");
}
第七步:设置下拉上拉的监听器
private void setListner() {
listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
//做下拉刷新
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//做上拉加载
}
});
}