Quản lý sự kiện chạm trong ViewGroup

Thử cách dùng Compose
Jetpack Compose là bộ công cụ giao diện người dùng được đề xuất cho Android. Tìm hiểu về cử chỉ trong Compose.

Bạn cần đặc biệt chú ý đến việc xử lý các sự kiện chạm trong ViewGroup vì thường thì ViewGroup có các phần tử con là mục tiêu của các sự kiện chạm khác với chính ViewGroup. Để đảm bảo mỗi thành phần hiển thị nhận được chính xác các sự kiện chạm dành cho thành phần đó, hãy ghi đè phương thức onInterceptTouchEvent().

Chặn sự kiện chạm trong ViewGroup

Phương thức onInterceptTouchEvent() được gọi bất cứ khi nào phát hiện thấy một sự kiện chạm trên bề mặt của ViewGroup, bao gồm cả trên bề mặt của các thành phần con. Nếu onInterceptTouchEvent() trả về true, thì MotionEvent sẽ bị chặn, nghĩa là không được truyền vào thành phần con mà sẽ được truyền vào phương thức onTouchEvent() của thành phần mẹ.

Phương thức onInterceptTouchEvent() cho phép thành phần hiển thị mẹ có cơ hội xem các sự kiện chạm trước khi các thành phần hiển thị con xem. Nếu bạn trả về true từ onInterceptTouchEvent(), thì thành phần hiển thị con trước đó xử lý các sự kiện chạm sẽ nhận được ACTION_CANCEL và các sự kiện từ thời điểm đó trở đi sẽ được gửi đến phương thức onTouchEvent() của thành phần hiển thị mẹ để xử lý như bình thường. onInterceptTouchEvent() cũng có thể trả về false và theo dõi các sự kiện khi chúng di chuyển xuống hệ phân cấp chế độ xem đến các mục tiêu thông thường, các mục tiêu này xử lý các sự kiện bằng onTouchEvent() của riêng chúng.

Trong đoạn mã sau, lớp MyViewGroup mở rộng ViewGroup. MyViewGroup chứa nhiều thành phần hiển thị con. Nếu bạn kéo ngón tay theo chiều ngang trên một thành phần hiển thị con, thành phần hiển thị con sẽ không còn nhận được sự kiện chạm và MyViewGroup sẽ xử lý các sự kiện chạm bằng cách cuộn nội dung của thành phần hiển thị con. Tuy nhiên, nếu bạn nhấn vào các nút trong thành phần hiển thị con hoặc cuộn thành phần hiển thị con theo chiều dọc, thì thành phần hiển thị mẹ sẽ không chặn các sự kiện chạm đó vì thành phần hiển thị con là mục tiêu dự kiến. Trong những trường hợp đó, onInterceptTouchEvent() sẽ trả về falseonTouchEvent() của lớp MyViewGroup sẽ không được gọi.

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.
        ...
    }
}

Xin lưu ý rằng ViewGroup cũng cung cấp một phương thức requestDisallowInterceptTouchEvent(). ViewGroup gọi phương thức này khi một thành phần con không muốn thành phần mẹ và các thành phần cấp trên chặn các sự kiện chạm bằng onInterceptTouchEvent().

Xử lý sự kiện ACTION_OUTSIDE

Nếu ViewGroup nhận được MotionEvent với ACTION_OUTSIDE, thì sự kiện sẽ không được gửi đến các phần tử con theo mặc định. Để xử lý MotionEvent bằng ACTION_OUTSIDE, hãy ghi đè dispatchTouchEvent(MotionEvent event) để gửi đến View thích hợp hoặc xử lý trong Window.Callback có liên quan, ví dụ: Activity.

Sử dụng hằng số ViewConfiguration

Đoạn mã trước đó sử dụng ViewConfiguration hiện tại để khởi chạy một biến có tên là mTouchSlop. Bạn có thể sử dụng lớp ViewConfiguration để truy cập vào các khoảng cách, tốc độ và thời gian phổ biến mà hệ thống Android sử dụng.

"Touch slop" (độ trễ chạm) đề cập đến khoảng cách tính bằng pixel mà thao tác chạm của người dùng có thể di chuyển trước khi cử chỉ được diễn giải là cuộn. Độ trễ cảm ứng thường được dùng để ngăn chặn việc cuộn vô tình khi người dùng đang thực hiện một thao tác chạm khác, chẳng hạn như chạm vào các phần tử trên màn hình.

Hai phương thức ViewConfiguration khác thường dùng là getScaledMinimumFlingVelocity()getScaledMaximumFlingVelocity(). Các phương thức này trả về tốc độ tối thiểu và tối đa tương ứng để bắt đầu một thao tác hất được đo bằng pixel/giây. Ví dụ:

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.
    }
}

Mở rộng khu vực có thể chạm của thành phần hiển thị con

Android cung cấp lớp TouchDelegate để cho phép thành phần mẹ mở rộng vùng có thể chạm của thành phần hiển thị con ngoài giới hạn của thành phần con. Điều này rất hữu ích khi thành phần con phải nhỏ nhưng cần có vùng chạm lớn hơn. Bạn cũng có thể sử dụng phương pháp này để thu nhỏ vùng cảm ứng của thành phần con.

Trong ví dụ sau, ImageButton là thành phần hiển thị uỷ quyền, tức là thành phần con có vùng cảm ứng mà thành phần mẹ mở rộng. Dưới đây là tệp bố cục:

<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>

Đoạn mã sau đây sẽ hoàn thành các nhiệm vụ này:

  • Lấy thành phần hiển thị mẹ và đăng Runnable trên luồng giao diện người dùng. Điều này đảm bảo rằng thành phần mẹ bố trí các thành phần con trước khi gọi phương thức getHitRect(). Phương thức getHitRect() lấy hình chữ nhật nhấn (hoặc vùng có thể chạm) của thành phần con trong toạ độ của thành phần mẹ.
  • Tìm thành phần hiển thị con ImageButton và gọi getHitRect() để lấy giới hạn của vùng có thể chạm của thành phần con.
  • Mở rộng giới hạn của hình chữ nhật nhấn của thành phần hiển thị con ImageButton.
  • Tạo bản sao TouchDelegate, truyền vào hình chữ nhật nhấn mở rộng và khung hiển thị con ImageButton dưới dạng tham số.
  • Đặt TouchDelegate trên thành phần hiển thị mẹ để các thao tác chạm trong giới hạn uỷ quyền chạm được định tuyến đến thành phần hiển thị con.

Với vai trò là trình uỷ quyền chạm cho thành phần hiển thị con ImageButton, thành phần hiển thị mẹ sẽ nhận được tất cả sự kiện chạm. Nếu sự kiện chạm xảy ra trong hình chữ nhật nhấn của thành phần con, thì thành phần mẹ sẽ chuyển sự kiện chạm đó cho thành phần con để xử lý.

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);
                }
            }
        });
    }
}