package com.rebound.myscroll;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ListView;
import android.widget.ScrollView;
/**
* MyListView
*
*/
public class MyListView extends ListView
{
private View inner;
private float y;
private Rect normal = new Rect();;
public MyListView(Context context, AttributeSet attrs)
{
super(context, attrs);
// this.smoothScrollTo(0, 0);
this.scrollTo(0, 0);
}
@Override
protected void onFinishInflate()
{
// if (getChildCount() > 0)
//{
// inner = getChildAt(0);
//}
inner=this;
System.out.println("inner//"+inner.toString());
}
@Override
public boolean onTouchEvent(MotionEvent ev)
{
if (inner == null)
{
return super.onTouchEvent(ev);
}
else
{
commOnTouchEvent(ev);
}
return super.onTouchEvent(ev);
}
public void commOnTouchEvent(MotionEvent ev)
{
int action = ev.getAction();
switch (action)
{
case MotionEvent.ACTION_DOWN:
y = ev.getY();
break;
case MotionEvent.ACTION_UP:
if (isNeedAnimation())
{
animation();
}
break;
case MotionEvent.ACTION_MOVE:
final float preY = y;
float nowY = ev.getY();
int deltaY = (int) (preY - nowY);
System.out.println("移动的距离::///"+deltaY);
// 下面的要注释掉,不然view会闪第一次,误用
// scrollBy(0, deltaY);
//scrollTo(0, deltaY);
y = nowY;
// 是否要改变位置
if (isNeedMove())
{
int left = inner.getLeft();
int top = inner.getTop();
int right = inner.getRight();
int bottom = inner.getBottom();
if (normal.isEmpty())
{
// 保存listview左上角这个坐标的位置,移动完后好回归原点
normal.set(left, top, right, bottom);
System.out.println("inner.getLeft()/inner.getTop()/inner.getRight()/inner.getBottom()"+left+" "+top+" "+right+" "+bottom);
}
// 改变listview的位置
inner.layout(left, top - deltaY, right, bottom - deltaY);
}
break;
default:
break;
}
}
// 动画
public void animation()
{
// 动画
TranslateAnimation ta = new TranslateAnimation(0, 0, inner.getTop(), normal.top);
ta.setDuration(200);
inner.startAnimation(ta);
// 回归最初位置
inner.layout(normal.left, normal.top, normal.right, normal.bottom);
normal.setEmpty();
}
// 看normal有没有保存listview的位置
public boolean isNeedAnimation()
{
return !normal.isEmpty();
}
// 是否符合反弹的条件
public boolean isNeedMove()
{
if (getFirstVisiblePosition()==0 || getLastVisiblePosition()==getAdapter().getCount()-1)
{
System.out.println("NeedMove");
return true;
}
System.out.println("not NeedMove");
return false;
}
}