在 Android 中模擬 iOS 的回彈效果,常見做法是自訂 ScrollView,攔截觸摸事件,並在頂部或底部拖動時移動內部版面,放開後再用動畫回到原位。
原始程式中的 size 參數用來控制跟手程度。size 等於 4 時,畫面大約跟隨手指移動四分之一距離;數值越小,位移越明顯。
int deltaY = (int)(preY - nowY) / size;
inner.layout(inner.getLeft(), yy, inner.getRight(), inner.getBottom() - deltaY);動畫部分可使用 TranslateAnimation,把子 View 從目前偏移位置移動回 normal.top。
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();Demo 下載:Android 回彈範例