1.PullToRefresh简介:
1.PullToRefresh第三方库可以用来做ListView,GridView,WebView,等控件的上拉,下拉刷新;
2.对应的类库中的类分别为PullToRefreshXxxView等;
2.PullToRefreshListView使用:
1.导入PullToRefresh依赖包;
2.在布局xml文件中如下:
<!-- 加载支持上拉,下拉刷新的ListView-->
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/pull_to_refresh_listview"
android:layout_height="fill_parent"
android:layout_width="fill_parent" />
- 3.Activity中java代码如下:
package com.longshun.animationdemo.customview;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.LinearInterpolator;
import android.widget.ArrayAdapter;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import java.util.ArrayList;
/**
* 使用PullToRefresh上拉加载,下拉刷新
*/
public class PullToRefreshDemo extends AppCompatActivity implements PullToRefreshBase.OnRefreshListener2 {
private PullToRefreshListView pullToRefreshView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pull_to_refresh_demo);
//1.相当于一个带刷新功能的ListView
pullToRefreshView = (PullToRefreshListView) findViewById(R.id.pull_to_refresh_listview);
//2.设置adapter,根据需求设置相应
ArrayList<String> data = new ArrayList<String>();
for (int i = 0; i < 50; i++) {
data.add("data " + i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
pullToRefreshView.setAdapter(adapter);
//3.设置pullToRefreshView的刷新模式,
//Mode.BOTH 既有上拉也有下拉
//PULL_FROM_START 下拉刷新
//PULL_FROM_END 上拉刷新
pullToRefreshView.setMode(PullToRefreshBase.Mode.BOTH);
//4.设置监听,滑动刷新时回调此方法
pullToRefreshView.setOnRefreshListener(this);
}
@Override
public void onPullDownToRefresh(PullToRefreshBase refreshView) {
//开始下拉刷新动画
pullToRefreshView.setRefreshing();
//TODO 开启异步加载数据或则其他操作
GetDataTask task = new GetDataTask();
task.execute();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase refreshView) {
//开始上拉刷新动画
pullToRefreshView.setRefreshing();
//TODO do something you need
GetDataTask task = new GetDataTask();
task.execute();
}
//开启异步任务加载数据
private class GetDataTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
//加载完毕,设置刷新完成,刷新动画效果结束
pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
}
}
}