Android仿IOS回彈效果 ScrollView回彈 總結
應項目中的需求 須要仿IOS 下拉回彈的效果 , 我在網上搜了非常多 大多數都是拿scrollview 改吧改吧
試了一些 發現總有點小問題
以下的代碼是我對大家公布的做了點小改動 認為沒太大問題
package com.example.myscrollview;
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.ScrollView;
/**
* Bolg :http://blog.csdn.net/aaawqqq?viewmode=contents
*
* @author baozi
*
*/
public class MyScrollView extends ScrollView {
// 拖動的距離 size = 4 的意思 僅僅同意拖動屏幕的1/4
private static final int size = 4;
private View inner;
private float y;
private Rect normal = new Rect();;
public MyScrollView(Context context) {
super(context);
}
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFinishInflate() {
if (getChildCount() > 0) {
inner = getChildAt(0);
}
}
@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()) {
// Log.v("mlguitar", "will up and animation");
animation();
}
break;
case MotionEvent.ACTION_MOVE:
final float preY = y;
float nowY = ev.getY();
/**
* size=4 表示 拖動的距離為屏幕的高度的1/4
*/
int deltaY = (int) (preY - nowY) / size;
// 滾動
// scrollBy(0, deltaY);
y = nowY;
// 當滾動到最上或者最下時就不會再滾動。這時移動布局
if (isNeedMove()) {
if (normal.isEmpty()) {
// 保存正常的布局位置
normal.set(inner.getLeft(), inner.getTop(),
inner.getRight(), inner.getBottom());
return;
}
int yy = inner.getTop() - deltaY;
// 移動布局
inner.layout(inner.getLeft(), yy, inner.getRight(),
inner.getBottom() - 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();
}
// 是否須要開啟動畫
public boolean isNeedAnimation() {
return !normal.isEmpty();
}
// 是否須要移動布局
public boolean isNeedMove() {
int offset = inner.getMeasuredHeight() - getHeight();
int scrollY = getScrollY();
if (scrollY == 0 || scrollY == offset) {
return true;
}
return false;
}
}
// ┏┓ ┏┓
// ┏┛┻━━━┛┻┓
// ┃ ┃
// ┃ ━ ┃
// ┃ ┳┛ ┗┳ ┃
// ┃ ┃
// ┃ ┻ ┃
// ┃ ┃
// ┗━┓ ┏━┛
// ┃ ┃ 神獸保佑
// ┃ ┃ 代碼無BUG!
// ┃ ┗━━━┓
// ┃ ┣┓
// ┃ ┏┛
// ┗┓┓┏━┳┓┏┛
// ┃┫┫ ┃┫┫
// ┗┻┛ ┗┻┛
代碼里面size 這個參數是用來設置拖動的距離
size= 4 代表 view僅僅會尾隨手指滑動1/4的距離
size=3 代表 尾隨手指滑動1/3的距離
其他同理
Demo 下載地址: http://download.csdn.net/detail/aaawqqq/7629533
假設有更好的效果請教我一下 謝謝
祝大家每天都能寫出好代碼...
