Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

打造下拉反彈效果:自定義 BounceScrollView 還原朋友圈封面交互

編輯:關於 Android 開發

微信朋友圈頂部的封面圖、QQ 空間說說的頭圖,都有一個共同的交互細節:往下拉時露出背景圖,鬆手後有彈性回彈的動畫。這種「阻尼拉伸 + 回彈」的手感,用 ScrollView 稍作改造就能實現。本文記錄完整思路。

1、效果預覽

(截圖來自早期的調試機,分辨率有限。)

實現原理

核心要點有三個:

  1. 攔截頂部與底部的越界拖動。ScrollView 本身在滾到頂或底時就不會再移動了,所以只要判斷 getScrollY() 是否為 0 或等於最大偏移,就能確定當前處於邊界。
  2. 手動改寫子 View 的布局位置。越界時不再依賴 ScrollView 自身的滾動,而是直接調用子 View 的 layout(),按手指移動距離的一半去偏移 top 與 bottom。除以 2 是為了製造阻尼感——手指移 100 像素,內容只動 50 像素。
  3. 用矩形記錄原始位置,鬆手時播放回彈動畫。第一次越界時把子 View 的正常位置存進 Rect,鬆手後用 TranslateAnimation 從當前偏移動畫回到原點,同時立刻把 layout 恢復正常值。

還有一個容易忽略的細節:ACTION_DOWN 時拿不到可靠的 y 坐標(因為此時事件已被子項消費),所以第一次 ACTION_MOVE 需要把 deltaY 歸零做初始化,從第二次移動開始才記錄準確數值。

2、BounceScrollView 實現

package com.org.scroll;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.TranslateAnimation;
import android.widget.ScrollView;

/** ScrollView 反彈效果的實現 */
public class BounceScrollView extends ScrollView {

    private View inner;              // 孩子 View
    private float y;                 // 按下時的 y 坐標
    private Rect normal = new Rect();// 保存正常布局位置
    private boolean isCount = false; // 是否開始計算

    public BounceScrollView(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) {
            commOnTouchEvent(ev);
        }
        return super.onTouchEvent(ev);
    }

    public void commOnTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                break;

            case MotionEvent.ACTION_UP:
                // 手指鬆開,若之前發生過偏移則播放回彈
                if (isNeedAnimation()) {
                    animation();
                    isCount = false;
                }
                break;

            case MotionEvent.ACTION_MOVE:
                final float preY = y;          // 按下時的 y 坐標
                float nowY = ev.getY();        // 當前 y 坐標
                int deltaY = (int) (preY - nowY);

                // 第一次移動無法得知初始 y,先歸零初始化
                if (!isCount) {
                    deltaY = 0;
                }
                y = nowY;

                if (isNeedMove()) {
                    // 首次偏移時記錄正常位置
                    if (normal.isEmpty()) {
                        normal.set(inner.getLeft(), inner.getTop(),
                                   inner.getRight(), inner.getBottom());
                    }
                    // 移動布局,deltaY 除以 2 形成阻尼感
                    inner.layout(inner.getLeft(),
                            inner.getTop() - deltaY / 2,
                            inner.getRight(),
                            inner.getBottom() - deltaY / 2);
                }
                isCount = true;
                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();
    }

    /**
     * 是否需要移動布局
     * inner.getMeasuredHeight() 取得的是控件總高度
     * getHeight() 取得的是屏幕(容器)高度
     */
    public boolean isNeedMove() {
        int offset = inner.getMeasuredHeight() - getHeight();
        int scrollY = getScrollY();
        // 0 是頂部,offset 是底部
        return scrollY == 0 || scrollY == offset;
    }
}

3、MainActivity

Activity 本身幾乎不需要邏輯,關鍵全在布局與 BounceScrollView 類:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
    }
}

4、activity_main 布局

布局的關鍵是:BounceScrollView 必須只有一個直接子 View(這裡用 LinearLayout 包裹全部內容),因為 onFinishInflate 只取 getChildAt(0)。背景圖設在 BounceScrollView 上,這樣下拉拉開內容時才會露出來。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/common_title_bg" />

    <com.org.scroll.BounceScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/coversation_bg"
        android:focusable="true"
        android:focusableInTouchMode="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingTop="10.0dip">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="600dp"
                android:layout_marginTop="16.0dip"
                android:background="#ffffffff"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/my_profile"
                    android:layout_width="fill_parent"
                    android:layout_height="44.0dip"
                    android:background="#800000ff"
                    android:clickable="true"
                    android:gravity="center_vertical"
                    android:paddingLeft="10.0dip"
                    android:paddingRight="10.0dip"
                    android:text="標題一" />

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16.0dip"
                    android:orientation="vertical">

                    <RelativeLayout
                        android:id="@+id/set_feedback"
                        android:layout_width="fill_parent"
                        android:layout_height="44.0dip"
                        android:background="#8000ffff"
                        android:clickable="true"
                        android:focusable="true">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_centerVertical="true"
                            android:layout_marginLeft="12.0dip"
                            android:duplicateParentState="true"
                            android:gravity="center_vertical"
                            android:text="反饋" />
                    </RelativeLayout>
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </com.org.scroll.BounceScrollView>
</LinearLayout>

可調參數與擴展方向

拿到這套代碼後,有幾個地方值得按實際需求微調:

阻尼係數。代碼中 deltaY / 2 的除數決定拉伸的「韌性」。數值越大越沉穩,越小越跟手。朋友圈那種偏硬的感覺,係數可以調到 3 甚至更高。

回彈時長。ta.setDuration(200) 控制回彈速度。若想更「Q 彈」,可以給動畫設置 OvershootInterpolator 讓它衝過原點再蕩回來。

雙向支持。當前實現依賴 TranslateAnimation 的 y 方向位移,理論上頂部與底部都能生效。若發現某個方向異常,通常是 isNeedMove() 中 offset 的計算邊界需要按實際布局再校準。

與 RecyclerView 結合。如果把內容換成 RecyclerView,更推薦直接繼承自它並覆寫 onTouchEvent,或者使用官方 SwipeRefreshLayout 搭配自定義 Header。不過 SwipeRefreshLayout 的動畫風格與這裡的「露出背景圖」不同,追求朋友圈同款視覺效果的話,本文這種手改 layout 的路子反而更直接。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved