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

Android 下拉反彈效果實作:自訂 BounceScrollView(仿朋友圈封面)

編輯:關於 Android 程式設計

微信朋友圈頂部的封面圖、QQ 空間說說的頭圖,都有同一種手感:手指往下拉,畫面就跟著往下讓出背景圖;一松手,內容「啪」地彈回原位。這類效果本質上還是用 ScrollView 做的,關鍵在於攔截觸摸事件、手動位移子 View,再補一段回縮動畫。

效果預覽

(截圖來自解析度較低的舊款測試機,僅供對照行為。)

核心類:BounceScrollView

整個效果的關鍵都在這個類裡,共有三件事要做:判斷是否已經滾到頂或底、在邊界處改寫子 View 的 layout 位置、松手時用 TranslateAnimation 補一段回彈。

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 final Rect normal = new Rect(); // 記錄正常狀態下的位置
    private boolean isCount = false; // 是否開始正式計算位移

    public BounceScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /** 視圖生成的最後一步,此時所有子 View 都已加入 */
    @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) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_UP:
                // 手指離開,若有位移則播放回彈動畫
                if (isNeedAnimation()) {
                    animation();
                    isCount = false;
                }
                break;

            case MotionEvent.ACTION_MOVE:
                // 第一次 MOVE 拿不到可靠的起始座標,先歸零
                float preY = y;
                float nowY = ev.getY();
                int deltaY = (int) (preY - nowY);
                if (!isCount) {
                    deltaY = 0;
                }
                y = nowY;

                if (isNeedMove()) {
                    if (normal.isEmpty()) {
                        normal.set(inner.getLeft(), inner.getTop(),
                                   inner.getRight(), inner.getBottom());
                    }
                    // 位移取一半,讓拖曳手感更柔和
                    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();
    }

    /**
     * 是否處於可拖曳的邊界。
     * getMeasuredHeight() 是內容總高,getHeight() 是控制項自身高度。
     */
    public boolean isNeedMove() {
        int offset = inner.getMeasuredHeight() - getHeight();
        int scrollY = getScrollY();
        return scrollY == 0 || scrollY == offset;
    }
}

Activity 與布局

Activity 端幾乎不需要寫邏輯,只要正常 setContentView() 即可:

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

布局的關鍵是用自訂的 com.org.scroll.BounceScrollView 取代原本的 ScrollView,並且在裡面只放一個直接子容器,背景圖則掛在 ScrollView 上,這樣拉開時才會露出底圖:

<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="wrap_content"
        android:orientation="vertical"
        android:paddingTop="10dip">
        <!-- 內容區,高度需大於螢幕才會出現邊界判斷 -->
    </LinearLayout>

</com.org.scroll.BounceScrollView>

可以再調整的地方

這份實作把位移固定除以 2,回彈時長固定 200 毫秒。實際專案中可以再微調:例如依拖曳距離做阻尼衰減、替回彈動畫換上插值器(OvershootInterpolator 手感更「Q」)、或只在頂部允許反彈而底部維持硬邊界。這些都只要在 commOnTouchEvent() 和 animation() 兩處動手即可。

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