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

動手實現 Android 小說閱讀器的滑動翻頁效果

編輯:關於 Android 程式設計

翻閱電子書時,我們常會遇到各種翻頁動畫,例如仿真翻頁、滑動翻頁等。本文將聚焦於最經典的一種——滑動翻頁,帶你實現一個流暢自然的翻頁效果。掌握核心的 onTouch 事件處理後,你完全可以舉一反三,延伸出更多炫酷的交互。

核心思路

整個方案通過自定義 ViewGroup(FlipperLayout)來管理三層 View:最底層(下一頁,初始不可見)、中間層(當前顯示頁)與最上層(上一頁,初始滑出屏幕)。藉由 Scroller 控制滑動動畫,並用 VelocityTracker 計算滑動速度,判斷用戶是「快速一掃」還是「緩慢拖動」,從而決定是否翻頁。

自定義翻頁容器

package com.example.testscroll.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

public class FlipperLayout extends ViewGroup {
    private Scroller mScroller;
    private VelocityTracker mVelocityTracker;
    private int mVelocityValue = 0;
    /** 商定這個滑動是否有效的距離 */
    private int limitDistance = 0;
    private int screenWidth = 0;
    private static final int MOVE_TO_LEFT = 0;
    private static final int MOVE_TO_RIGHT = 1;
    private static final int MOVE_NO_RESULT = 2;
    private int mTouchResult = MOVE_NO_RESULT;
    private int mDirection = MOVE_NO_RESULT;
    private static final int MODE_NONE = 0;
    private static final int MODE_MOVE = 1;
    private int mMode = MODE_NONE;
    private View mScrollerView = null;
    private View currentTopView = null;
    private View currentShowView = null;
    private View currentBottomView = null;

    public FlipperLayout(Context context) { super(context); init(context); }
    public FlipperLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); }
    public FlipperLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context); }

    private void init(Context context) {
        mScroller = new Scroller(context);
        screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        limitDistance = screenWidth / 3;
    }

    public void initFlipperViews(TouchListener listener, View currentBottomView, View currentShowView, View currentTopView) {
        this.currentBottomView = currentBottomView;
        this.currentShowView = currentShowView;
        this.currentTopView = currentTopView;
        setTouchResultListener(listener);
        addView(currentBottomView);
        addView(currentShowView);
        addView(currentTopView);
        currentTopView.scrollTo(-screenWidth, 0);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(width, height);
        for (int i = 0; i < getChildCount(); i++) {
            getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    private int startX = 0;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (!mScroller.isFinished()) { break; }
                startX = (int) ev.getX();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        obtainVelocityTracker(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                // ... 省略滑動跟手邏輯(判斷方向、模式、scrollTo 等)
                break;
            case MotionEvent.ACTION_UP:
                // ... 省略抬手判定(根據距離或速度決定翻頁或復位)
                resetVariables();
                postInvalidate();
                break;
        }
        return true;
    }

    private void resetVariables() {
        mDirection = MOVE_NO_RESULT;
        mMode = MODE_NONE;
        startX = 0;
        releaseVelocityTracker();
    }

    private TouchListener mListener;
    private void setTouchResultListener(TouchListener listener) { this.mListener = listener; }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mScroller.computeScrollOffset()) {
            mScrollerView.scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();
        }
        // ... 翻頁完成後切換三層 View 的邏輯
    }

    private void obtainVelocityTracker(MotionEvent event) {
        if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); }
        mVelocityTracker.addMovement(event);
    }

    private void releaseVelocityTracker() {
        if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; }
    }

    public interface TouchListener {
        int MOVE_TO_LEFT = 0;
        int MOVE_TO_RIGHT = 1;
        View createView(final int direction);
        boolean currentIsFirstPage();
        boolean currentIsLastPage();
        boolean whetherHasPreviousPage();
        boolean whetherHasNextPage();
    }
}

Activity 中的分頁與渲染

在 Activity 中,我們從 assets 讀取小說文本,按固定字數(例如每次 400 字)切分內容,並通過實現 TouchListener 接口,動態生成承載文本的新 View。文本索引的維護是關鍵,它決定了翻到哪一頁、是否還有上一頁或下一頁。

public class MainActivity extends Activity implements OnClickListener, TouchListener {
    private String text = "";
    private int textLenght = 0;
    private static final int COUNT = 400;
    private int currentTopEndIndex = 0;
    private int currentShowEndIndex = 0;
    private int currentBottomEndIndex = 0;

    // 通過 ReadingThread 從 assets/text.txt 讀取文本後,用 Handler 初始化三層 View
    // createView(direction) 負責根據方向生成新頁面並更新索引
    // whetherHasPreviousPage / whetherHasNextPage 判斷可否滑動
    // currentIsFirstPage / currentIsLastPage 判斷邊界
}

頁面布局

單頁布局用 LinearLayout 承載一個 TextView,右側再放一條細豎線作為視覺分隔。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" >
    <TextView android:id="@+id/textview" android:layout_width="0dp" android:layout_height="match_parent"
        android:layout_weight="1.0" android:background="#666666" android:gravity="center"
        android:text="新建的View" android:textColor="@android:color/white" android:textSize="16sp" android:visibility="visible" />
    <View android:layout_width="5dp" android:layout_height="match_parent" android:background="#FFFF00" />
</LinearLayout>

Activity 布局則直接把自定義的 FlipperLayout 作為根容器。

<com.example.testscroll.view.FlipperLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools" android:id="@+id/container"
    android:layout_width="match_parent" android:layout_height="match_parent" >
</com.example.testscroll.view.FlipperLayout>

關於速度計算器

為什麼要引入 VelocityTracker?它的作用是識別「快速滑動」動作。即使滑動距離不足屏幕的三分之一,只要手指劃過的速度足夠快,也應判定為一次有效的翻頁,這樣的交互才更貼近真實的閱讀體驗。

需要說明的是,這裡展示的僅是滑動翻頁的視覺效果,並不包含完整的章節拆分邏輯。雖然代碼相對樸素,但其中的事件分發與動畫思路頗具借鑒價值,歡迎大家交流探討更好的方案。

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