您的位置:首页 > 其它

弹性ListView

2015-12-09 20:03 309 查看

在网上找了好多关于弹性ListView的文章,虽然大多提供了两种方法,但是本人测试了很多次,那种复写overScrollBy()的方法都不能够实现想要的功能,最后找到了一个(http://blog.csdn.net/eastman520/article/details/19043973#comments),整理了之后发表在这里,希望对大家的学习能有帮助。

具有弹性效果的ListView。主要是实现父类dispatchTouchEvent方法和OnGestureListener中onScroll方法。不过这种方式只能实现顶部的弹性,下方的弹性有待进一步研究。

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ListView;

public class MyListView extends ListView implements OnGestureListener{
private Context context = null;
//判断是否出界,初始值为否
private boolean outBound = false;
private int distance;
private int firstOut;

public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}

public MyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
}

public MyListView(Context context) {
super(context);
this.context = context;
}

GestureDetector lisGestureDetector = new GestureDetector(context, this);

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (!lisGestureDetector.onTouchEvent(event)) {
outBound = false;
} else {
outBound = true;
}
//添加矩形
Rect rect = new Rect();
getLocalVisibleRect(rect);
//添加动画
TranslateAnimation am = new TranslateAnimation( 0, 0, -rect.top, 0);
am.setDuration(300);
startAnimation(am);
scrollTo(0, 0);
return super.dispatchTouchEvent(event);
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,float distanceY) {
int firstPos = getFirstVisiblePosition();
int lastPos = getLastVisiblePosition();
View firstView = getChildAt(firstPos);
if (!outBound)
firstOut = (int) e2.getRawY();
//第一个可见视图不为空并且越界了或者第一个可见的视图的最上方坐标为0,或者距离y轴距离小于0
if (firstView != null&& (outBound || (firstPos == 0 && firstView.getTop() == 0 && distanceY < 0))) {
distance = firstOut - (int) e2.getRawY();
scrollTo(0, distance / 3);
return true;
}
return false;
}

@Override
public boolean onDown(MotionEvent e) {
return false;
}

@Override
public void onShowPress(MotionEvent e) {
}

@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}

@Override
public void onLongPress(MotionEvent e) {
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY) {
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: