管理 ViewGroup 中的觸控事件

試試 Compose
Jetpack Compose 是 Android 推薦的 UI 工具包。瞭解 Compose 中的手勢。

ViewGroup 中處理觸控事件時,請特別注意,因為 ViewGroup 通常會有子項,這些子項是不同觸控事件的目標,而非 ViewGroup 本身。如要確保每個檢視區塊正確接收到預期觸控事件,請覆寫 onInterceptTouchEvent() 方法。

在 ViewGroup 中攔截觸控事件

系統偵測到 ViewGroup 表面 (包括子項表面) 的觸控事件時,就會呼叫 onInterceptTouchEvent() 方法。如果 onInterceptTouchEvent() 傳回 true,系統會攔截 MotionEvent,也就是說,系統不會將 MotionEvent 傳遞至子項,而是傳遞至上層的 onTouchEvent() 方法。

onInterceptTouchEvent() 方法可讓父項在子項之前查看觸控事件。如果從 onInterceptTouchEvent() 傳回 true,先前處理觸控事件的子項檢視區塊會收到 ACTION_CANCEL,而之後的事件會傳送至父項的 onTouchEvent() 方法,以進行一般處理。onInterceptTouchEvent() 也可以傳回 false,並在事件沿著檢視區塊階層傳送至一般目標時監控事件,這些目標會使用自己的 onTouchEvent() 處理事件。

在下列程式碼片段中,MyViewGroup 類別會擴充 ViewGroupMyViewGroup 包含多個子檢視區塊。如果手指在子項檢視區塊上水平拖曳,子項檢視區塊就不會再收到觸控事件,而 MyViewGroup 會透過捲動內容處理觸控事件。不過,如果輕觸子項檢視區塊中的按鈕,或垂直捲動子項檢視區塊,父項不會攔截這些觸控事件,因為子項是預期目標。在這種情況下,onInterceptTouchEvent() 會傳回 false,且不會呼叫 MyViewGroup 類別的 onTouchEvent()

Kotlin

class MyViewGroup @JvmOverloads constructor(
        context: Context,
        private val mTouchSlop: Int = ViewConfiguration.get(context).scaledTouchSlop
) : ViewGroup(context) {
    ...
    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        // This method only determines whether you want to intercept the motion.
        // If this method returns true, onTouchEvent is called and you can do
        // the actual scrolling there.
        return when (ev.actionMasked) {
            // Always handle the case of the touch gesture being complete.
            MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                // Release the scroll.
                mIsScrolling = false
                false // Don't intercept the touch event. Let the child handle it.
            }
            MotionEvent.ACTION_MOVE -> {
                if (mIsScrolling) {
                    // You're currently scrolling, so intercept the touch event.
                    true
                } else {

                    // If the user drags their finger horizontally more than the
                    // touch slop, start the scroll.

                    // Left as an exercise for the reader.
                    val xDiff: Int = calculateDistanceX(ev)

                    // Touch slop is calculated using ViewConfiguration constants.
                    if (xDiff > mTouchSlop) {
                        // Start scrolling!
                        mIsScrolling = true
                        true
                    } else {
                        false
                    }
                }
            }
            ...
            else -> {
                // In general, don't intercept touch events. The child view
                // handles them.
                false
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        // Here, you actually handle the touch event. For example, if the action
        // is ACTION_MOVE, scroll this container. This method is only called if
        // the touch event is intercepted in onInterceptTouchEvent.
        ...
    }
}

Java

public class MyViewGroup extends ViewGroup {

    private int mTouchSlop;
    ...
    ViewConfiguration vc = ViewConfiguration.get(view.getContext());
    mTouchSlop = vc.getScaledTouchSlop();
    ...
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // This method only determines whether you want to intercept the motion.
        // If this method returns true, onTouchEvent is called and you can do
        // the actual scrolling there.

        final int action = MotionEventCompat.getActionMasked(ev);

        // Always handle the case of the touch gesture being complete.
        if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
            // Release the scroll.
            mIsScrolling = false;
            return false; // Don't intercept touch event. Let the child handle it.
        }

        switch (action) {
            case MotionEvent.ACTION_MOVE: {
                if (mIsScrolling) {
                    // You're currently scrolling, so intercept the touch event.
                    return true;
                }

                // If the user drags their finger horizontally more than the
                // touch slop, start the scroll.

                // Left as an exercise for the reader.
                final int xDiff = calculateDistanceX(ev);

                // Touch slop is calculated using ViewConfiguration constants.
                if (xDiff > mTouchSlop) {
                    // Start scrolling.
                    mIsScrolling = true;
                    return true;
                }
                break;
            }
            ...
        }

        // In general, don't intercept touch events. The child view handles them.
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Here, you actually handle the touch event. For example, if the
        // action is ACTION_MOVE, scroll this container. This method is only
        // called if the touch event is intercepted in onInterceptTouchEvent.
        ...
    }
}

請注意,ViewGroup 也提供 requestDisallowInterceptTouchEvent() 方法。當子項不希望父項及其祖先透過 onInterceptTouchEvent() 攔截觸控事件時,ViewGroup 會呼叫這個方法。

處理 ACTION_OUTSIDE 事件

如果 ViewGroup 收到含有 ACTION_OUTSIDEMotionEvent,系統預設不會將事件調派給子項。如要使用 ACTION_OUTSIDE 處理 MotionEvent,請覆寫 dispatchTouchEvent(MotionEvent event),將其分派至適當的 View,或在相關的 Window.Callback 中處理,例如 Activity

使用 ViewConfiguration 常數

上述程式碼片段會使用目前的 ViewConfiguration 初始化名為 mTouchSlop 的變數。您可以使用 ViewConfiguration 類別存取 Android 系統使用的常見距離、速度和時間。

「觸控斜率」是指使用者觸控時,在手勢解讀為捲動前可移動的像素距離。觸控容錯通常用於防止使用者執行其他觸控作業時 (例如觸控螢幕上的元素) 發生誤觸捲動。

另外兩種常用的 ViewConfiguration 方法是 getScaledMinimumFlingVelocity()getScaledMaximumFlingVelocity()。這些方法會分別傳回啟動擺動的最小和最大速度,以每秒像素為單位。例如:

Kotlin

private val vc: ViewConfiguration = ViewConfiguration.get(context)
private val mSlop: Int = vc.scaledTouchSlop
private val mMinFlingVelocity: Int = vc.scaledMinimumFlingVelocity
private val mMaxFlingVelocity: Int = vc.scaledMaximumFlingVelocity
...
MotionEvent.ACTION_MOVE -> {
    ...
    val deltaX: Float = motionEvent.rawX - mDownX
    if (Math.abs(deltaX) > mSlop) {
        // A swipe occurs, do something.
    }
    return false
}
...
MotionEvent.ACTION_UP -> {
    ...
    if (velocityX in mMinFlingVelocity..mMaxFlingVelocity && velocityY < velocityX) {
        // The criteria are satisfied, do something.
    }
}

Java

ViewConfiguration vc = ViewConfiguration.get(view.getContext());
private int mSlop = vc.getScaledTouchSlop();
private int mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
private int mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
...
case MotionEvent.ACTION_MOVE: {
    ...
    float deltaX = motionEvent.getRawX() - mDownX;
    if (Math.abs(deltaX) > mSlop) {
        // A swipe occurs, do something.
    }
...
case MotionEvent.ACTION_UP: {
    ...
    } if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
            && velocityY < velocityX) {
        // The criteria are satisfied, do something.
    }
}

擴大子項檢視區塊的可觸控區域

Android 提供 TouchDelegate 類別,讓父項可將子項檢視區塊的可觸控區域擴展至子項邊界以外。如果子項必須很小,但需要較大的觸控區域,這就非常實用。您也可以使用這種方法縮小子項的觸控區域。

在下列範例中,ImageButton 是 _委派檢視區塊_,也就是父項擴展觸控區域的子項。以下是版面配置檔案:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/parent_layout"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context=".MainActivity" >

     <ImageButton android:id="@+id/button"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:background="@null"
          android:src="@drawable/icon" />
</RelativeLayout>

下列程式碼片段會完成這些工作:

  • 取得父項檢視區塊,並在 UI 執行緒上發布 Runnable。這樣可確保父項在呼叫 getHitRect() 方法前,會先配置子項。getHitRect() 方法會取得父項座標中的子項命中矩形 (或可觸控區域)。
  • 找出 ImageButton 子項檢視區塊,並呼叫 getHitRect() 取得子項可觸控區域的邊界。
  • 擴展 ImageButton 子項檢視區塊的觸控矩形邊界。
  • 例項化 TouchDelegate,並傳入展開的命中矩形和 ImageButton 子項檢視區塊做為參數。
  • 在父項檢視區塊中設定 TouchDelegate,以便將觸控委派範圍內的觸控事件轉送至子項。

父項檢視區塊會以 ImageButton 子項檢視區塊的觸控委派身分,接收所有觸控事件。如果觸控事件發生在子項的命中矩形內,父項會將觸控事件傳遞給子項處理。

Kotlin

public class MainActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Post in the parent's message queue to make sure the parent lays out
        // its children before you call getHitRect().
        findViewById<View>(R.id.parent_layout).post {
            // The bounds for the delegate view, which is an ImageButton in this
            // example.
            val delegateArea = Rect()
            val myButton = findViewById<ImageButton>(R.id.button).apply {
                isEnabled = true
                setOnClickListener {
                    Toast.makeText(
                            this@MainActivity,
                            "Touch occurred within ImageButton touch region.",
                            Toast.LENGTH_SHORT
                    ).show()
                }

                // The hit rectangle for the ImageButton.
                getHitRect(delegateArea)
            }

            // Extend the touch area of the ImageButton beyond its bounds on the
            // right and bottom.
            delegateArea.right += 100
            delegateArea.bottom += 100

            // Set the TouchDelegate on the parent view so that touches within
            // the touch delegate bounds are routed to the child.
            (myButton.parent as? View)?.apply {
                // Instantiate a TouchDelegate. "delegateArea" is the bounds in
                // local coordinates of the containing view to be mapped to the
                // delegate view. "myButton" is the child view that receives
                // motion events.
                touchDelegate = TouchDelegate(delegateArea, myButton)
            }
        }
    }
}

Java

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Get the parent view.
        View parentView = findViewById(R.id.parent_layout);

        parentView.post(new Runnable() {
            // Post in the parent's message queue to make sure the parent lays
            // out its children before you call getHitRect().
            @Override
            public void run() {
                // The bounds for the delegate view, which is an ImageButton in
                // this example.
                Rect delegateArea = new Rect();
                ImageButton myButton = (ImageButton) findViewById(R.id.button);
                myButton.setEnabled(true);
                myButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(MainActivity.this,
                                "Touch occurred within ImageButton touch region.",
                                Toast.LENGTH_SHORT).show();
                    }
                });

                // The hit rectangle for the ImageButton.
                myButton.getHitRect(delegateArea);

                // Extend the touch area of the ImageButton beyond its bounds on
                // the right and bottom.
                delegateArea.right += 100;
                delegateArea.bottom += 100;

                // Instantiate a TouchDelegate. "delegateArea" is the bounds in
                // local coordinates of the containing view to be mapped to the
                // delegate view. "myButton" is the child view that receives
                // motion events.
                TouchDelegate touchDelegate = new TouchDelegate(delegateArea,
                        myButton);

                // Set the TouchDelegate on the parent view so that touches
                // within the touch delegate bounds are routed to the child.
                if (View.class.isInstance(myButton.getParent())) {
                    ((View) myButton.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });
    }
}