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

Android View 體系(二):實現 View 滑動的六種方法

編輯:關於 Android 程式設計

一、View 滑動的共通思路

View 滑動是自定義控件的基礎,開發中也難免遇到。其實無論哪一種實現方式,基本思想都是類似的:當觸摸事件傳到 View 時,系統記下觸摸點的座標;手指移動時記下新的座標並算出偏移量;再透過偏移量修改 View 的座標。

差別只在於「修改座標」這一步用了哪個 API。本文說明六種做法:layout()、offsetLeftAndRight() 與 offsetTopAndBottom()、LayoutParams、動畫、scrollTo 與 scrollBy,以及 Scroller。屬性動畫的細節留待下一篇深入。

二、六種實現方式

1. layout()

View 繪製時會呼叫 onLayout() 來設定顯示位置,因此我們也可以直接修改 left、top、right、bottom 這四個屬性來控制座標。

先自定義一個 View,在 onTouchEvent() 中取得觸摸點座標:

public boolean onTouchEvent(MotionEvent event) {
    // 取得手指處的橫座標與縱座標
    int x = (int) event.getX();
    int y = (int) event.getY();
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        lastX = x;
        lastY = y;
        break;
    // ...

接著在 ACTION_MOVE 中計算偏移量,呼叫 layout() 重新擺放自己:

case MotionEvent.ACTION_MOVE:
    // 計算移動的距離
    int offsetX = x - lastX;
    int offsetY = y - lastY;
    // 呼叫 layout 方法重新放置它的位置
    layout(getLeft() + offsetX, getTop() + offsetY,
           getRight() + offsetX, getBottom() + offsetY);
    break;

每次移動都呼叫 layout() 對自己重新佈局,達到移動效果。

完整程式碼(CustomView.java):

package com.example.liuwangshu.moonviewslide;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class CustomView extends View {
    private int lastX;
    private int lastY;

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

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

    public CustomView(Context context) {
        super(context);
    }

    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            lastX = x;
            lastY = y;
            break;
        case MotionEvent.ACTION_MOVE:
            int offsetX = x - lastX;
            int offsetY = y - lastY;
            layout(getLeft() + offsetX, getTop() + offsetY,
                   getRight() + offsetX, getBottom() + offsetY);
            break;
        }
        return true;
    }
}

布局中引用:

<?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="vertical">

    <com.example.liuwangshu.moonviewslide.CustomView
        android:id="@+id/customview"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_margin="50dp"
        android:background="@android:color/holo_red_light" />
</LinearLayout>

實作提醒:ACTION_MOVE 中缺少 lastX = x 與 lastY = y 的更新,否則偏移量會以 ACTION_DOWN 的位置為基準不斷累加,導致 View 飛出螢幕。另外,layout() 只能由父容器呼叫,在 View 內部直接呼叫自己雖可運行,但並非官方推薦用法——它屬於 ViewGroup 的 API,實務上更常見的是搭配 offsetLeftAndRight 使用。

2. offsetLeftAndRight() 與 offsetTopAndBottom()

這兩個方法與 layout() 效果相近,使用更簡潔。把 ACTION_MOVE 中的程式碼換成:

case MotionEvent.ACTION_MOVE:
    int offsetX = x - lastX;
    int offsetY = y - lastY;
    offsetLeftAndRight(offsetX);   // 對 left 與 right 進行偏移
    offsetTopAndBottom(offsetY);   // 對 top 與 bottom 進行偏移
    break;

它們的優勢在於只更新座標而不觸發重新佈局,效能上比 layout() 更好。

3. 修改 LayoutParams

LayoutParams 保存著一個 View 的佈局參數,改動它同樣能達到移動效果:

LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
layoutParams.leftMargin = getLeft() + offsetX;
layoutParams.topMargin = getTop() + offsetY;
setLayoutParams(layoutParams);

因為父容器是 LinearLayout,所以用 LinearLayout.LayoutParams;若父容器是 RelativeLayout 就要換成 RelativeLayout.LayoutParams。也可以用通用的 MarginLayoutParams:

ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();
layoutParams.leftMargin = getLeft() + offsetX;
layoutParams.topMargin = getTop() + offsetY;
setLayoutParams(layoutParams);

這種方式會觸發 requestLayout(),效能成本較高,適合移動頻率不高的場景。

4. 動畫

用 View 動畫來移動。在 res 下新建 anim 目錄並建立 translate.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <translate
        android:duration="1000"
        android:fromXDelta="0"
        android:toXDelta="300" />
</set>

Java 中引用:

mCustomView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.translate));

屬性動畫則更簡潔,讓 CustomView 在 1000 毫秒內沿 X 軸右移 300 像素:

ObjectAnimator.ofFloat(mCustomView, "translationX", 0, 300).setDuration(1000).start();

兩者的關鍵差異:View 動畫只改變繪製效果,View 的真正位置沒變,因此觸摸事件的回應區域仍在原處;屬性動畫改的是 translationX 這個真實屬性,事件命中區域會跟著移動。若需要「看起來動了、摸也摸得到」的效果,請用屬性動畫。

5. scrollTo 與 scrollBy

scrollTo(x, y) 移動到一個絕對座標,scrollBy(dx, dy) 則移動相對增量 dx、dy。scrollBy 最終也是呼叫 scrollTo 完成的。

需要特別理解的是:這兩個方法移動的是 View 的內容,而非 View 本身。在 ViewGroup 中使用時,移動的是它所有的子 View。因此,View 內容往某方向滾動,等價於 View 本身往反方向移動——這也是為什麼呼叫時要傳負值:

((View) getParent()).scrollBy(-offsetX, -offsetY);

另外,scrollX/scrollY 的值恆為非正數(只能往左上方滾動),超出內容範圍的滾動會被系統約束,這些特性在實作時都要納入考量。

6. Scroller

scrollTo/scrollBy 的缺點是瞬間完成,使用者體驗不佳。Scroller 能實現帶過渡效果的滑動——這個過程不是瞬間完成,而是在一段時間內逐步推進。

但要注意:Scroller 本身不能實現 View 滑動,它需要搭配 View 的 computeScroll() 才能產生彈性滑動效果。

以下實現 CustomView 平滑右移。

首先初始化 Scroller:

public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mScroller = new Scroller(context);
}

接著覆寫 computeScroll()。系統在繪製 View 時會於 draw() 中呼叫這個方法;我們在其中呼叫 scrollTo(),並透過 Scroller 不斷取得目前的捲動值,每移動一小段就呼叫 invalidate() 觸發重繪,重繪又會呼叫 computeScroll(),形成連續的平滑移動:

@Override
public void computeScroll() {
    super.computeScroll();
    if (mScroller.computeScrollOffset()) {
        ((View) getParent()).scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
    }
    // 透過不斷重繪,不斷呼叫 computeScroll
    invalidate();
}

然後呼叫 Scroller.startScroll()。在 CustomView 中寫一個 smoothScrollTo(),於 2000 毫秒內沿 X 軸平移 delta 像素:

public void smoothScrollTo(int destX, int destY) {
    int scrollX = getScrollX();
    int delta = destX - scrollX;
    // 2000 毫秒內滑向 destX
    mScroller.startScroll(scrollX, 0, delta, 0, 2000);
    invalidate();
}

在 Activity 中呼叫:

// 使用 Scroller 進行平滑移動
mCustomView.smoothScrollTo(-400, 0);

這裡設定 CustomView 沿 X 軸向右平移 400 像素(因為 scrollTo 傳負值代表內容右移,所以目標值是 -400)。

這段程式碼有個值得修正的細節:invalidate() 被放在 if 之外,導致動畫結束後仍會持續重繪,形成無意義的空轉。應改為只在 computeScrollOffset() 回傳 true 時才呼叫 invalidate(),讓迴圈在動畫完成後自然停止。

三、六種方式的比較

layout():會觸發重新佈局,效能較差,且屬於父容器的 API,不建議在 View 內部使用。
offsetLeftAndRight / offsetTopAndBottom:只更新座標,不觸發 layout,是這六種中位移類操作裡效能最好的。
LayoutParams:直觀易懂,但 setLayoutParams 會觸發 requestLayout,頻率高時需注意。
View 動畫:只改視覺,不改真實位置,事件區域不跟著動。
scrollTo / scrollBy:移動的是內容而非 View 本身,且只能往左上方捲動,需要搭配座標換算。
Scroller:不是位移手段,而是為 scrollTo 提供時間軸,實現平滑過渡。

實務上的常見組合是:用 Scroller 驅動時間軸,在 computeScroll 中呼叫 scrollTo 完成位移。這也是各類「平滑滾動到目標位置」效果背後的標準做法。

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