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

讓 Android Gallery 一次只滑動一張圖片

編輯:關於 Android 程式設計

Gallery 預設的 fling 行為是依滑動速度決定一次滾動幾張,滑快一點就一口氣跳好幾張。若你要的是「一次一張」的相簿瀏覽體驗,覆寫 onFling() 是最乾淨的做法。

思路

判斷滑動方向,把它換算成對應的方向鍵事件,再交給 Gallery 原本的 onKeyDown() 處理。這樣做等於把「連續滾動」改成「單步移動」,一次 fling 只走一格。

DetialGallery.java

package gongzibai.co.cc;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Gallery;

public class DetialGallery extends Gallery {

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

    private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
        return e2.getX() > e1.getX();
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2,
            float velocityX, float velocityY) {
        int keyCode;
        if (isScrollingLeft(e1, e2)) {
            keyCode = KeyEvent.KEYCODE_DPAD_LEFT;
        } else {
            keyCode = KeyEvent.KEYCODE_DPAD_RIGHT;
        }
        onKeyDown(keyCode, null);
        return true;
    }
}

版面配置

因為換成了自訂檢視,XML 中要用完整類別名稱:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/widget32"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <gongzibai.co.cc.DetialGallery
        android:id="@+id/widget1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:spacing="10dp" />

</LinearLayout>

幾個提醒

覆寫 onFling 之後,velocityX 與 velocityY 就完全沒被使用了。如果你希望「輕滑不動、用力滑才換」,可以在這裡加一層速度門檻,超過才呼叫 onKeyDown,否則回傳 false 交給原邏輯處理。

另外,Gallery 在 API 14 之後已被標記為 deprecated,官方建議改用 HorizontalScrollView 搭配 Adapter,或直接使用 RecyclerView 加水平方向的 LinearLayoutManager——後者對「一次一張」這種需求支援得更好,內建就有 snap 行為可以搭配。

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