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

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

編輯:關於 Android 開發

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

1. View 滑動簡介

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

本文介紹六種滑動方法:layout()、offsetLeftAndRight() 與 offsetTopAndBottom()、LayoutParams、動畫、scrollTo 與 scrollBy,以及 Scroller。屬性動畫會在下一篇詳細說明。

2. 六種滑動方法

layout()

View 繪製時會呼叫 onLayout() 來設定顯示位置,因此我們可以透過修改 left、top、right、bottom 來控制座標。先在 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(getLeft() + offsetX, getTop() + offsetY,
           getRight() + offsetX, getBottom() + offsetY);
    break;

每次移動都呼叫 layout() 對自己重新佈局,就能達到移動效果。自定義 View 完整程式碼:

public class CustomView extends View {
    private int lastX, lastY;
    public CustomView(Context context, AttributeSet attrs) { super(context, attrs); }
    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;
    }
}

佈局中引用這個自定義 View 即可:

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

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;

LayoutParams(改變佈局參數)

LayoutParams 保存了一個 View 的佈局參數,改動它的 margin 即可移動 View:

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

父容器不同要用對應的 LayoutParams(例如 RelativeLayout.LayoutParams);也可用通用的 ViewGroup.MarginLayoutParams。

動畫

可用 View 動畫移動,在 res 下建立 anim 目錄並新增 translate.xml:

<set xmlns:android="https://schemas.android.com/apk/res/android">
    <translate android:duration="1000"
        android:fromXDelta="0" android:toXDelta="300" />
</set>
mCustomView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.translate));

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

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

scrollTo 與 scrollBy

scrollTo(x, y) 移動到具體座標點,scrollBy(dx, dy) 則是移動增量,scrollBy 最終也會呼叫 scrollTo。它們移動的是 View 的「內容」;若在 ViewGroup 中使用則移動其所有子 View。要讓 CustomView 隨手指移動,需把偏移量設為負值:

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

Scroller

用 scrollTo/scrollBy 滑動是瞬間完成的,體驗不佳。Scroller 能實現帶過渡效果的滑動,但它本身不能實現滑動,必須搭配 View 的 computeScroll()。先初始化 Scroller:

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

重寫 computeScroll(),在繪製時透過 Scroller 取得當前滾動值,每滑一小段就 invalidate() 重繪,重繪又會觸發 computeScroll(),如此反覆串接即形成平滑移動:

@Override
public void computeScroll() {
    super.computeScroll();
    if (mScroller.computeScrollOffset()) {
        ((View) getParent()).scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
    }
    invalidate();
}

再寫一個 smoothScrollTo(),呼叫 startScroll() 在指定時間內平移:

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

最後在 Activity 中呼叫即可,例如讓 CustomView 沿 X 軸右移 400 像素:

mCustomView.smoothScrollTo(-400, 0);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved