ViewGroup のタッチイベントを管理する

ViewGroup でのタッチイベントの処理には細心の注意を払ってください。ViewGroup 自体とは異なるタッチイベントのターゲットとなる子をViewGroup 使用するのが一般的であるためです。各ビューが目的のタッチイベントを正しく受け取るようにするには、onInterceptTouchEvent() メソッドをオーバーライドします。

ViewGroup でタッチイベントをインターセプトする

onInterceptTouchEvent() メソッドは、ViewGroup の表面(子の表面も含む)でタッチイベントが検出されるたびに呼び出されます。onInterceptTouchEvent()true を返すと、MotionEvent がインターセプトされます。つまり、これは子ではなく、親の onTouchEvent() メソッドに渡されます。

onInterceptTouchEvent() メソッドを使用すると、子より前にタッチイベントを確認する機会を親に与えることができます。onInterceptTouchEvent() から true を返すと、以前にタッチイベントを処理していた子ビューは ACTION_CANCEL を受け取り、それ以降のイベントは通常の処理として親の onTouchEvent() メソッドに送信されます。また、onInterceptTouchEvent()false を返し、通常のターゲットまでビュー階層を下るときにイベントを監視できます。このターゲットは独自の onTouchEvent() でイベントを処理します。

次のスニペットでは、MyViewGroup クラスが ViewGroup を拡張しています。MyViewGroup には複数の子ビューが含まれます。子ビューで指を横方向にドラッグすると、子ビューはタッチイベントを取得しなくなり、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 イベントを処理する

ViewGroupACTION_OUTSIDEMotionEvent を受け取った場合、デフォルトではイベントがその子にディスパッチされません。MotionEventACTION_OUTSIDE で処理するには、dispatchTouchEvent(MotionEvent event) をオーバーライドして適切な View にディスパッチするか、関連する Window.CallbackActivity など)で処理します。

ViewConfiguration 定数を使用する

上記のスニペットでは、現在の ViewConfiguration を使用して、mTouchSlop という変数を初期化しています。ViewConfiguration クラスを使用すると、Android システムで使用される一般的な距離、速度、時間にアクセスできます。

「タッチスロップ」とは、ユーザーのタップがスクロールとして解釈される前にユーザーのタップが移動できる距離をピクセル単位で表したものです。タッチスロップは通常、ユーザーが別のタッチ操作(画面上の要素へのタップなど)を行っているときに誤ってスクロールしないようにするために使用されます。

一般的に使用される他の 2 つの 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);
                }
            }
        });
    }
}