管理 ViewGroup 中的觸控事件

處理 ViewGroup 中的觸控事件需要特別留意,因為 ViewGroup 包含適用於不同觸控事件的子項,而不是 ViewGroup 本身。為確保每個檢視畫面都能正確接收預期的觸控事件,請覆寫 onInterceptTouchEvent() 方法。

攔截 ViewGroup 中的觸控事件

每當在 ViewGroup 表面偵測到觸控事件 (包括其子項表面) 時,就會呼叫 onInterceptTouchEvent() 方法。如果 onInterceptTouchEvent() 傳回 true,系統會攔截 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);
                }
            }
        });
    }
}