代码有注释 ,就不详细说明了
package com.example.android.imagedownloader;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ListView;
public class XScrollListView extends ListView {
/**
* 记录按下的位置
*/
private float mLastDownY;
/**
* 滑动的距离
*/
private int mDistance;
/**
* 标志是向上拉(mDistace<0),还是向下拉(mDistance>0)
* */
private boolean mPositive;
/**
* 每次恢复的像素
*/
private int mStep = 10;
public XScrollListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public XScrollListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public XScrollListView(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastDownY = ev.getY();
break;
case MotionEvent.ACTION_UP:
// 当不上点击的时候才去复原
if (mDistance != 0) {
mStep = 1;
mPositive = (mDistance >= 0);
post(restoreRunnable);
return true;
}
mLastDownY = 0f;
mDistance = 0;
break;
case MotionEvent.ACTION_MOVE:
Log.d("diors", "/////ACTION_MOVE = " + mLastDownY);
mDistance = (int) (mLastDownY - ev.getY());
Log.d("diors", "/////mDistance = " + mDistance);
// 在第一行可见或者最后一行可见的时候才允许拉动
if ((mDistance < 0 && getFirstVisiblePosition() == 0 && getChildAt(
0).getTop() == 0)
|| (mDistance > 0 && getLastVisiblePosition() == getCount() - 1)) {
mDistance /= 2;
scrollTo(0, mDistance);
return true;
}
break;
default:
break;
}
return super.onTouchEvent(ev);
}
/**
* 恢复到原始位置
* */
private void restoreListView() {
mDistance += mDistance > 0 ? -mStep : mStep;
scrollTo(0, mDistance);
Log.d("diors", "/////mPositive = " + mPositive);
Log.d("diors", "/////mDistance = " + mDistance);
// 当mDistance移动距离恢复的时候,跳出
if ((mPositive && mDistance <= 0) || (!mPositive && mDistance >= 0)) {
scrollTo(0, 0);
mDistance = 0;
mLastDownY = 0f;
return;
}
Log.d("diors", "/////mStep = " + mStep);
mStep += 1;
postDelayed(restoreRunnable, 10);
}
private Runnable restoreRunnable = new Runnable() {
@Override
public void run() {
restoreListView();
}
};
}