管理 ViewGroup 中的觸控事件

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

ViewGroup 中處理觸控事件時,請特別小心,因為 ViewGroup 通常會包含子項,而這些子項是不同觸控事件的目標,而非 ViewGroup 本身。為確保每個檢視畫面都能正確接收專屬的觸控事件,請覆寫 onInterceptTouchEvent() 方法。

攔截 ViewGroup 中的觸控事件

只要在 ViewGroup 的表面 (包括其子項的表面) 偵測到觸控事件,系統就會呼叫 onInterceptTouchEvent() 方法。如果 onInterceptTouchEvent() 傳回 trueMotionEvent 就會遭到攔截,也就是說,它不會傳遞至子項,而是傳遞至父項的 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 系統使用的常見距離、速度和時間。

「Touch slop」是指使用者手指在手勢被解讀為捲動之前,可以偏離的像素距離。觸控滑動通常用於防止使用者在執行其他觸控操作 (例如觸碰螢幕元素) 時,不小心捲動畫面。

另外兩個常用的 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 子檢視畫面的命中矩形邊界。
  • 將展開的命中矩形和 ImageButton 子檢視區塊做為參數,並以此例項化 TouchDelegate
  • 在父項檢視畫面上設定 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);
                }
            }
        });
    }
}