上次写了一个上拉加载,下拉刷新,但上拉加载时没有可旋转的动画图片,所以这次又写了一个。
首先需要三个类:
第一个:
public interface Pullable {
/**
* 判断是否可以下拉,如果不需要下拉功能可以直接return false
*
* @return true如果可以下拉否则返回false
*/
boolean canPullDown();
/**
* 判断是否可以上拉,如果不需要上拉功能可以直接return false
*
* @return true如果可以上拉否则返回false
*/
boolean canPullUp();
}
第二个:
public class PulltorefershLayout extends RelativeLayout {
public PulltorefershLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public static final String TAG = "PullToRefreshLayout";
// 初始状态
public static final int INIT = 0;
// 释放刷新
public static final int RELEASE_TO_REFRESH = 1;
// 正在刷新
public static final int REFRESHING = 2;
// 释放加载
public static final int RELEASE_TO_LOAD = 3;
// 正在加载
public static final int LOADING = 4;
// 操作完毕
public static final int DONE = 5;
// 当前状态
private int state = INIT;
// 刷新回调接口
private OnRefreshListener mListener;
// 刷新成功
public static final int SUCCEED = 0;
// 刷新失败
public static final int FAIL = 1;
// 按下Y坐标,上一个事件点Y坐标
private float downY, lastY;
// 下拉的距离。注意:pullDownY和pullUpY不可能同时不为0
public float pullDownY = 0;
// 上拉的距离
private float pullUpY = 0;
// 释放刷新的距离
private float refreshDist = 200;
// 释放加载的距离
private float loadmoreDist = 200;
private MyTimer timer;
// 回滚速度
public float MOVE_SPEED = 8;
// 第一次执行布局
private boolean isLayout = false;
// 在刷新过程中滑动操作
private boolean isTouch = false;
// 手指滑动距离与下拉头的滑动距离比,中间会随正切函数变化
private float radio = 2;
// 下拉箭头的转180°动画
private RotateAnimation rotateAnimation;
// 均匀旋转动画
private RotateAnimation refreshingAnimation;
// 下拉头
private View refreshView;
// 下拉的箭头
private View pullView;
// 正在刷新的图标
private View refreshingView;
// 刷新结果图标
private View refreshStateImageView;
// 刷新结果:成功或失败
private TextView refreshStateTextView;
// 上拉头
private View loadmoreView;
// 上拉的箭头
private View pullUpView;
// 正在加载的图标
private View loadingView;
// 加载结果图标
private View loadStateImageView;
// 加载结果:成功或失败
private TextView loadStateTextView;
// 实现了Pullable接口的View
private View pullableView;
// 过滤多点触碰
private int mEvents;
// 这两个变量用来控制pull的方向,如果不加控制,当情况满足可上拉又可下拉时没法下拉
private boolean canPullDown = true;
private boolean canPullUp = true;
Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 回弹速度随下拉距离moveDeltaY增大而增大
MOVE_SPEED = (float) (8 + 5 * Math.tan(Math.PI / 2
/ getMeasuredHeight() * (pullDownY + Math.abs(pullUpY))));
if (!isTouch) {
// 正在刷新,且没有往上推的话则悬停,显示"正在刷新..."
if (state == REFRESHING && pullDownY <= refreshDist) {
pullDownY = refreshDist;
timer.cancel();
} else if (state == LOADING && -pullUpY <= loadmoreDist) {
pullUpY = -loadmoreDist;
timer.cancel();
}
}
if (pullDownY > 0)
pullDownY -= MOVE_SPEED;
else if (pullUpY < 0)
pullUpY += MOVE_SPEED;
if (pullDownY < 0) {
// 已完成回弹
pullDownY = 0;
pullView.clearAnimation();
// 隐藏下拉头时有可能还在刷新,只有当前状态不是正在刷新时才改变状态
if (state != REFRESHING && state != LOADING)
changeState(INIT);
timer.cancel();
requestLayout();
}
if (pullUpY > 0) {
// 已完成回弹
pullUpY = 0;
pullUpView.clearAnimation();
// 隐藏下拉头时有可能还在刷新,只有当前状态不是正在刷新时才改变状态
if (state != REFRESHING && state != LOADING)
changeState(INIT);
timer.cancel();
requestLayout();
}
Log.d("handle", "handle");
// 刷新布局,会自动调用onLayout
requestLayout();
if (pullDownY + Math.abs(pullUpY) == 0)
timer.cancel();
}
};
private Context mContext;
public void setOnRefreshListener(OnRefreshListener listener) {
mListener = listener;
}
// public PulltorefershLayout(Context context)
// {
// super(context);
// initView(context);
// }
public PulltorefershLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public PulltorefershLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
private void initView(Context context) {
mContext = context;
timer = new MyTimer(updateHandler);
rotateAnimation = (RotateAnimation) AnimationUtils.loadAnimation(
context, R.anim.reserve_anim);
refreshingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(
context, R.anim.rotating);
// 添加匀速转动动画
LinearInterpolator lir = new LinearInterpolator();
rotateAnimation.setInterpolator(lir);
refreshingAnimation.setInterpolator(lir);
}
private void hide() {
timer.schedule(5);
}
/**
* 完成刷新操作,显示刷新结果。注意:刷新完成后一定要调用这个方法
*/
/**
* @param refreshResult
* PullToRefreshLayout.SUCCEED代表成功ullToRefreshLayout.FAIL代表失败
*/
public void refreshFinish(int refreshResult) {
refreshingView.clearAnimation();
refreshingView.setVisibility(View.GONE);
switch (refreshResult) {
case SUCCEED:
// // 刷新成功
refreshStateImageView.setVisibility(View.VISIBLE);
refreshStateTextView.setText("刷新成功");
refreshStateImageView
.setBackgroundResource(R.drawable.refresh_succeed);
break;
case FAIL:
default:
// 刷新失败
refreshStateImageView.setVisibility(View.VISIBLE);
refreshStateTextView.setText("刷新失败");
refreshStateImageView
.setBackgroundResource(R.drawable.refresh_failed);
break;
}
if (pullDownY > 0) {
// 刷新结果停留1秒
new Handler() {
@Override
public void handleMessage(Message msg) {
changeState(DONE);
hide();
}
}.sendEmptyMessageDelayed(0, 1000);
} else {
changeState(DONE);
hide();
}
}
/**
* 加载完毕,显示加载结果。注意:加载完成后一定要调用这个方法
*
* @param refreshResult
* PullToRefreshLayout.SUCCEED代表成功ullToRefreshLayout.FAIL失败
*/
public void loadmoreFinish(int refreshResult) {
loadingView.clearAnimation();
loadingView.setVisibility(View.GONE);
switch (refreshResult) {
case SUCCEED:
// 加载成功
loadStateImageView.setVisibility(View.VISIBLE);
loadStateTextView.setText("加载成功");
loadStateImageView.setBackgroundResource(R.drawable.load_succeed);
break;
case FAIL:
default:
// 加载失败
loadStateImageView.setVisibility(View.VISIBLE);
loadStateTextView.setText("加载失败");
loadStateImageView.setBackgroundResource(R.drawable.load_failed);
break;
}
if (pullUpY < 0) {
// 刷新结果停留1秒
new Handler() {
@Override
public void handleMessage(Message msg) {
changeState(DONE);
hide();
}
}.sendEmptyMessageDelayed(0, 1000);
} else {
changeState(DONE);
hide();
}
}
private void changeState(int to) {
state = to;
switch (state) {
case INIT:
// 下拉布局初始状态
refreshStateImageView.setVisibility(View.GONE);
refreshStateTextView.setText("下拉刷新");
pullView.clearAnimation();
pullView.setVisibility(View.VISIBLE);
// 上拉布局初始状态
loadStateImageView.setVisibility(View.GONE);
loadStateTextView.setText("上拉加载更多");
pullUpView.clearAnimation();
pullUpView.setVisibility(View.VISIBLE);
break;
case RELEASE_TO_REFRESH:
// 释放刷新状态
refreshStateTextView.setText("释放立即刷新");
pullView.startAnimation(rotateAnimation);
break;
case REFRESHING:
// 正在刷新状态
pullView.clearAnimation();
refreshingView.setVisibility(View.VISIBLE);
pullView.setVisibility(View.INVISIBLE);
refreshingView.startAnimation(refreshingAnimation);
refreshStateTextView.setText("正在刷新...");
break;
case RELEASE_TO_LOAD:
// 释放加载状态
loadStateTextView.setText("释放立即加载");
pullUpView.startAnimation(rotateAnimation);
break;
case LOADING:
// 正在加载状态
pullUpView.clearAnimation();
loadingView.setVisibility(View.VISIBLE);
pullUpView.setVisibility(View.INVISIBLE);
loadingView.startAnimation(refreshingAnimation);
loadStateTextView.setText("正在加载...");
break;
case DONE:
// 刷新或加载完毕,啥都不做
break;
}
}
/**
* 不限制上拉或下拉
*/
private void releasePull() {
canPullDown = true;
canPullUp = true;
}
/*
* (非 Javadoc)由父控件决定是否分发事件,防止事件冲突
*
* @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
downY = ev.getY();
lastY = downY;
timer.cancel();
mEvents = 0;
releasePull();
break;
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_POINTER_UP:
// 过滤多点触碰
mEvents = -1;
break;
case MotionEvent.ACTION_MOVE:
if (mEvents == 0) {
if (pullDownY > 0
|| (((Pullable) pullableView).canPullDown()
&& canPullDown && state != LOADING)) {
// 可以下拉,正在加载时不能下拉
// 对实际滑动距离做缩小,造成用力拉的感觉
pullDownY = pullDownY + (ev.getY() - lastY) / radio;
if (pullDownY < 0) {
pullDownY = 0;
canPullDown = false;
canPullUp = true;
}
if (pullDownY > getMeasuredHeight())
pullDownY = getMeasuredHeight();
if (state == REFRESHING) {
// 正在刷新的时候触摸移动
isTouch = true;
}
} else if (pullUpY < 0
|| (((Pullable) pullableView).canPullUp() && canPullUp && state != REFRESHING)) {
pullUpY = pullUpY + (ev.getY() - lastY) / radio;
if (pullUpY > 0) {
pullUpY = 0;
canPullDown = true;
canPullUp = false;
}
if (pullUpY < -getMeasuredHeight())
pullUpY = -getMeasuredHeight();
if (state == LOADING) {
isTouch = true;
}
} else
releasePull();
} else
mEvents = 0;
lastY = ev.getY();
radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight()
* (pullDownY + Math.abs(pullUpY))));
if (pullDownY > 0 || pullUpY < 0)
requestLayout();
if (pullDownY > 0) {
if (pullDownY <= refreshDist
&& (state == RELEASE_TO_REFRESH || state == DONE)) {
changeState(INIT);
}
if (pullDownY >= refreshDist && state == INIT) {
changeState(RELEASE_TO_REFRESH);
}
} else if (pullUpY < 0) {
if (-pullUpY <= loadmoreDist
&& (state == RELEASE_TO_LOAD || state == DONE)) {
changeState(INIT);
}
if (-pullUpY >= loadmoreDist && state == INIT) {
changeState(RELEASE_TO_LOAD);
}
}
if ((pullDownY + Math.abs(pullUpY)) > 8) {
ev.setAction(MotionEvent.ACTION_CANCEL);
}
break;
case MotionEvent.ACTION_UP:
if (pullDownY > refreshDist || -pullUpY > loadmoreDist)
{
isTouch = false;
}
if (state == RELEASE_TO_REFRESH) {
changeState(REFRESHING);
if (mListener != null)
mListener.onRefresh(this);
} else if (state == RELEASE_TO_LOAD) {
changeState(LOADING);
if (mListener != null)
mListener.onLoadMore(this);
}
hide();
default:
break;
}
super.dispatchTouchEvent(ev);
return true;
}
/**
*
*
*/
private class AutoRefreshAndLoadTask extends
AsyncTask<Integer, Float, String> {
@Override
protected String doInBackground(Integer... params) {
while (pullDownY < 4 / 3 * refreshDist) {
pullDownY += MOVE_SPEED;
publishProgress(pullDownY);
try {
Thread.sleep(params[0]);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
changeState(REFRESHING);
if (mListener != null)
mListener.onRefresh(PulltorefershLayout.this);
hide();
}
@Override
protected void onProgressUpdate(Float... values) {
if (pullDownY > refreshDist)
changeState(RELEASE_TO_REFRESH);
requestLayout();
}
}
/**
*
*/
public void autoRefresh() {
AutoRefreshAndLoadTask task = new AutoRefreshAndLoadTask();
task.execute(20);
}
/**
*
*/
public void autoLoad() {
pullUpY = -loadmoreDist;
requestLayout();
changeState(LOADING);
// 加载操作
if (mListener != null)
mListener.onLoadMore(this);
}
// http://blog.csdn.net/zhongkejingwang/article/details/38868463
private void initView() {
// 初始化下拉布局
pullView = refreshView.findViewById(R.id.pull_icon);
refreshStateTextView = (TextView) refreshView
.findViewById(R.id.state_tv);
refreshingView = refreshView.findViewById(R.id.refreshing_icon);
refreshStateImageView = refreshView.findViewById(R.id.state_iv);
// 初始化上拉布局
pullUpView = loadmoreView.findViewById(R.id.pullup_icon);
loadStateTextView = (TextView) loadmoreView
.findViewById(R.id.loadstate_tv);
loadingView = loadmoreView.findViewById(R.id.loading_icon);
loadStateImageView = loadmoreView.findViewById(R.id.loadstate_iv);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d("Test", "Test");
if (!isLayout) {
// 这里是第一次进来的时候做一些初始化
refreshView = getChildAt(0);
pullableView = getChildAt(1);
loadmoreView = getChildAt(2);
isLayout = true;
initView();
refreshDist = ((ViewGroup) refreshView).getChildAt(0)
.getMeasuredHeight();
loadmoreDist = ((ViewGroup) loadmoreView).getChildAt(0)
.getMeasuredHeight();
}
// 改变子控件的布局,这里直接用(pullDownY + pullUpY)作为偏移量,这样就可以不对当前状态作区分
refreshView.layout(0,
(int) (pullDownY + pullUpY) - refreshView.getMeasuredHeight(),
refreshView.getMeasuredWidth(), (int) (pullDownY + pullUpY));
pullableView.layout(0, (int) (pullDownY + pullUpY),
pullableView.getMeasuredWidth(), (int) (pullDownY + pullUpY)
+ pullableView.getMeasuredHeight());
loadmoreView.layout(0,
(int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight(),
loadmoreView.getMeasuredWidth(),
(int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight()
+ loadmoreView.getMeasuredHeight());
}
class MyTimer {
private Handler handler;
private Timer timer;
private MyTask mTask;
public MyTimer(Handler handler) {
this.handler = handler;
timer = new Timer();
}
public void schedule(long period) {
if (mTask != null) {
mTask.cancel();
mTask = null;
}
mTask = new MyTask(handler);
timer.schedule(mTask, 0, period);
}
public void cancel() {
if (mTask != null) {
mTask.cancel();
mTask = null;
}
}
class MyTask extends TimerTask {
private Handler handler;
public MyTask(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
handler.obtainMessage().sendToTarget();
}
}
}
/**
* 刷新加载回调接口
*
* @author chenjing
*
*/
public interface OnRefreshListener {
/**
* 刷新操作
*/
void onRefresh(PulltorefershLayout pullToRefreshLayout);
/**
* 加载操作
*/
void onLoadMore(PulltorefershLayout pullToRefreshLayout);
}
}
------------------------------------anim-------------------------------------------
---------reserve_anim-------
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="100"
android:fillAfter="true"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="0"
android:toDegrees="180">
</rotate>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1500"
android:fillAfter="true"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="-1"
android:toDegrees="360">
</rotate>
---------rotating-------
第三个:
public class PullableListview extends ListView implements Pullable {
public PullableListview(Context context) {
super(context);
}
public PullableListview(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PullableListview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean canPullDown() {
if (getCount() == 0) {
return true;
} else if (getFirstVisiblePosition() == 0
&& getChildAt(0).getTop() >= 0) {
return true;
} else
return false;
}
@Override
public boolean canPullUp() {
if (getCount() == 0) {
return true;
} else if (getLastVisiblePosition() == (getCount() - 1)) {
if (getChildAt(getLastVisiblePosition() - getFirstVisiblePosition()) != null
&& getChildAt(
getLastVisiblePosition()
- getFirstVisiblePosition()).getBottom() <= getMeasuredHeight())
return true;
}
return false;
}
//布局
主布局
<com.example.pulltorefersh.PulltorefershLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/pull_layout1" >
<include layout="@layout/refersh_head"/>
<com.example.pulltorefersh.PullableListview
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listview" />
<include layout="@layout/load_more"/>
</com.example.pulltorefersh.PulltorefershLayout>
---------refersh_head布局------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:paddingBottom="20dp"
android:paddingTop="20dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<ImageView
android:id="@+id/pull_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="60dp"
android:background="@drawable/pull_icon_big" />
<ImageView
android:id="@+id/refreshing_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="60dp"
android:background="@drawable/refreshing"
android:visibility="gone" />
<TextView
android:id="@+id/state_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="下拉刷新..."
android:textColor="#f00"
android:textSize="16sp" />
<ImageView
android:id="@+id/state_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:layout_toLeftOf="@id/state_tv"
android:visibility="gone" />
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
-------------load_more布局------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingBottom="20dp"
android:paddingTop="20dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<ImageView
android:id="@+id/pullup_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="60dp"
android:background="@drawable/pullup_icon_big" />
<ImageView
android:id="@+id/loading_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="60dp"
android:background="@drawable/loading"
android:visibility="gone" />
<TextView
android:id="@+id/loadstate_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="上拉加载..."
android:textColor="#f0f"
android:textSize="16sp" />
<ImageView
android:id="@+id/loadstate_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:layout_toLeftOf="@id/loadstate_tv"
android:visibility="gone" />
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
pull_layout1 = (PulltorefershLayout) view
.findViewById(R.id.pull_layout1);
pull_layout1.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(PulltorefershLayout pullToRefreshLayout) {
pull_layout1.refreshFinish(PulltorefershLayout.SUCCEED);
}
@Override
public void onLoadMore(PulltorefershLayout pullToRefreshLayout) {
pull_layout1.loadmoreFinish(PulltorefershLayout.SUCCEED);
}
});
}