使用ListView將位置拖到頂部和底部默認(rèn)是沒有回彈效果的柠傍,為了增加這個(gè)效果,方法如下:
1完沪、開啟overScrollMode為always
在布局中 android:overScrollMode="always"
或在代碼中 setOverScrollMode(View.OVER_SCROLL_ALWAYS);
2域庇、繼承l(wèi)istview 覆蓋overScrollBy方法嵌戈,并且利用反射機(jī)制修改陰影效果為透明
public class PullListview extends ListView {
private static final int MAX_Y_OVERSCROLL_DISTANCE = 100;
private Context mContext;
private int mMaxYOverscrollDistance;
public PullListview(Context context) {
super(context);
mContext = context;
initPullListview();
}
public PullListview(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
initPullListview();
}
public PullListview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
initPullListview();
}
private void initPullListview() {
// get the density of the screen and do some maths with it on the max
// overscroll distance
// variable so that you get similar behaviors no matter what the screen
// size
final DisplayMetrics metrics = mContext.getResources()
.getDisplayMetrics();
final float density = metrics.density;
mMaxYOverscrollDistance = (int)(density * MAX_Y_OVERSCROLL_DISTANCE);
// this.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
try {
Class < ? > c = (Class < ? > ) Class.forName(AbsListView.class.getName());
Field egtField = c.getDeclaredField("mEdgeGlowTop");
Field egbBottom = c.getDeclaredField("mEdgeGlowBottom");
egtField.setAccessible(true);
egbBottom.setAccessible(true);
Object egtObject = egtField.get(this); // this 指的是ListiVew實(shí)例
Object egbObject = egbBottom.get(this);
// egtObject.getClass() 實(shí)際上是一個(gè) EdgeEffect 其中有兩個(gè)重要屬性 mGlow mEdge
// 并且這兩個(gè)屬性都是Drawable類型
Class < ? > cc = (Class < ? > ) Class.forName(egtObject.getClass()
.getName());
Field mGlow = cc.getDeclaredField("mGlow");
mGlow.setAccessible(true);
mGlow.set(egtObject, new ColorDrawable(Color.TRANSPARENT));
mGlow.set(egbObject, new ColorDrawable(Color.TRANSPARENT));
Field mEdge = cc.getDeclaredField("mEdge");
mEdge.setAccessible(true);
mEdge.set(egtObject, new ColorDrawable(Color.TRANSPARENT));
mEdge.set(egbObject, new ColorDrawable(Color.TRANSPARENT));
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressLint("NewApi")
@Override
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX,
int scrollY, int scrollRangeX, int scrollRangeY,
int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
// This is where the magic happens, we have replaced the incoming
// maxOverScrollY with our own custom variable mMaxYOverscrollDistance;
return super.overScrollBy(deltaX, deltaY, scrollX, scrollY,
scrollRangeX, scrollRangeY, maxOverScrollX,
mMaxYOverscrollDistance, isTouchEvent);
}
}