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

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

Chặn các 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ả bề mặt của phần tử con. Nếu onInterceptTouchEvent() trả về true, thì MotionEvent bị chặn, nghĩa là truy vấn không được truyền vào phần tử con mà được truyền vào phương thức onTouchEvent() của phần tử mẹ.

Phương thức onInterceptTouchEvent() cung cấp cho thành phần mẹ cơ hội xem các sự kiện chạm trước khi các thành phần con cháu thực hiện. Nếu bạn trả về true từ onInterceptTouchEvent(), thì khung hiển thị con trước đó đang 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 được gửi đến phương thức onTouchEvent() của thành phần mẹ để xử lý thông 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 khung hiển thị đến các mục tiêu thông thường, giúp xử lý các sự kiện bằng onTouchEvent() riêng.

Trong đoạn mã sau, lớp MyViewGroup sẽ mở rộng ViewGroup. MyViewGroup chứa nhiều khung hiển thị con. Nếu bạn kéo ngón tay qua thành phần hiển thị con theo chiều ngang, thì thành phần hiển thị con đó sẽ không còn nhận các sự kiện chạm nữa, 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ị đó. 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 mẹ sẽ không chặn các sự kiện chạm đó vì thành phần con đó là mục tiêu dự định. 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 thành phần con không muốn thành phần mẹ và đối tượng 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 MotionEventACTION_OUTSIDE, thì theo mặc định, sự kiện này sẽ không được gửi đến các phần tử con. Để 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ý đối tượng đó trong Window.Callback liên quan, chẳng hạn như Activity.

Sử dụng các hằng số ViewConfiguration

Đoạn mã trước sử dụng ViewConfiguration hiện tại để khởi chạy 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.

"Độ lệch cảm ứng" đề 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 hiểu là cuộn. Độ dốc cảm ứng thường được dùng để ngăn việc vô tình cuộn khi người dùng đang thực hiện một thao tác chạm khác, chẳng hạn như nhấn vào các thành phần trên màn hình.

Hai phương thức ViewConfiguration thường dùng khác là getScaledMinimumFlingVelocity()getScaledMaximumFlingVelocity(). Các phương thức này trả về vận tốc tối thiểu và tối đa tương ứng để bắt đầu cử chỉ 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 chế độ xem con

Android cung cấp lớp TouchDelegate để giúp thành phần mẹ có thể mở rộng vùng có thể chạm của thành phần hiển thị con bên ngoài giới hạn của thành phần con. Tính năng này hữu ích khi thành phần hiển thị phải nhỏ nhưng cần có vùng cảm ứng 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à chế độ xem _Delegate_, tức là chế độ xem con có khu vực cảm ứng mà phần tử 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 tác vụ sau:

  • Lấy khung hiển thị mẹ và đăng một Runnable lên luồng giao diện người dùng. Việc này đảm bảo rằng phần tử mẹ sắp xếp các phần tử con trước khi gọi phương thức getHitRect(). Phương thức getHitRect() lấy hình chữ nhật lượt truy cập của thành phần con (hoặc vùng có thể chạm) 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 khu vực con có thể chạm vào.
  • Mở rộng ranh giới của hình chữ nhật đã nhấn vào chế độ xem con ImageButton.
  • Tạo thực thể cho TouchDelegate, truyền vào hình chữ nhật lượt truy cập mở rộng và thành phần hiển thị con ImageButton dưới dạng thông số.
  • Thiết lập TouchDelegate trên khung hiển thị mẹ để các thao tác chạm trong giới hạn uỷ quyền thao tác chạm được chuyển đến khung hiển thị con.

Trong vai trò uỷ quyền chạm cho khung hiển thị con ImageButton, khung hiển thị mẹ sẽ nhận được mọi 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ẽ truyề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);
                }
            }
        });
    }
}