Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 中讓 View 滑動的六種實作方式

開發時常會遇到「這個 View 要能拖動」的需求。本文把常見的六種做法整理出來。其實核心思路完全一致:監聽手勢的觸控座標,據此改變 View 的位置,視覺上就產生了滑動。

一、用 Layout 重新配置位置

把滑動後的目標座標交給 layout(),讓它重新配置 View 的位置,畫面上看起來就是 View 移動了。

先自訂一個 View:

package com.example.testdragview;

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

public class DragView extends View {

    private int lastX;
    private int lastY;

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

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

    public DragView(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 offX = x - lastX;
                int offY = y - lastY;
                // 呼叫 layout 重新配置位置
                layout(getLeft() + offX, getTop() + offY,
                       getRight() + offX, getBottom() + offY);
                break;
        }
        return true;
    }
}

重點就在 onTouchEvent:記錄上一次與這一次的座標,把差值餵給 layout()。另外注意回傳值必須是 true,代表我們要消化掉這個觸摸事件。

接著把它放進布局:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.testdragview.DragView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="#FF0000" />

</LinearLayout>

執行後就能自由拖動了。

上面用的是 getX() / getY(),也就是視圖座標系的值。若改用 getRawX() / getRawY() 取得絕對座標,同樣能完成滑動,但有一個關鍵差異:在 ACTION_MOVE 階段必須即時更新 lastX 與 lastY,否則「上一次的座標」會失準,因為絕對座標的基準是螢幕而非控件本身。

更多詳情見請繼續閱讀下一頁的精彩內容: https://www.linuxidc.com/Linux/2015-11/125390p2.htm

Copyright © Linux教程網 All Rights Reserved