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

Xử lý sự kiện chạm trong ViewGroup luôn chăm sóc đặc biệt vì thông thường ViewGroup có phần tử con là mục tiêu cho các mục tiêu khác nhau sự kiện chạm so với chính ViewGroup. Để đảm bảo mỗi chế độ xem đều nhận được chính xác sự kiện chạm dành cho nó, hãy ghi đè onInterceptTouchEvent() .

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

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

Phương thức onInterceptTouchEvent() cho phép cha mẹ xem các sự kiện chạm trước khi các con của nó thực hiện. Nếu bạn trả về true từ onInterceptTouchEvent(), 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 nhà xuất bả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 đi 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 với onTouchEvent() của riêng chúng.

Trong đoạn mã sau, lớp MyViewGroup mở rộng ViewGroup. MyViewGroup chứa nhiều khung hiển thị con. Nếu bạn kéo ngón tay trên một chế độ xem dành cho trẻ em theo chiều ngang, khung hiển thị con không còn nhận được các sự kiện chạm nữa, còn MyViewGroup xử lý thao tác chạm các sự kiện bằng cách cuộn nội dung của sự kiện đó. Tuy nhiên, nếu bạn nhấn vào các nút trong chế độ xem trẻ em hoặc cuộn chế độ xem của trẻ xem 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à dự định . Trong những trường hợp đó, onInterceptTouchEvent() sẽ trả về falseonTouchEvent() của lớp MyViewGroup 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 requestDisallowInterceptTouchEvent() . ViewGroup gọi phương thức này khi con không muốn phần tử mẹ và phần tử con đố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 MotionEvent có một ACTION_OUTSIDE, theo mặc định, sự kiện đó sẽ không được gửi đến các phần tử con. Cách xử lý MotionEvent bằng ACTION_OUTSIDE, hoặc ghi đè dispatchTouchEvent(MotionEvent event) để gửi đến View hoặc hãy xử lý trong trường hợp Window.Callback—cho ví dụ: Activity.

Dùng hằng số ViewConfiguration

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

"Touch slop" (Thanh trượt cảm ứng) là khoảng cách tính bằng pixel mà người dùng có thể chạm vào trước khi cử chỉ được thực hiện được hiểu là cuộn. Tính năng trượt cảm ứng thường 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ư chạm 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 lần lượt trả về vận tốc tối thiểu và tối đa để bắt đầu một cử chỉ hất được đo lường tính 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 dành cho trẻ em

Android cung cấp TouchDelegate lớp để tham gia phần tử mẹ có thể mở rộng khu vực có thể chạm của khung hiển thị con ra ngoài giới hạn của phần tử con đó. Chiến dịch này rất hữu ích khi trẻ nhỏ nhưng cần vùng cảm ứng lớn hơn. Bạn cũng có thể sử dụng để thu nhỏ vùng cảm ứng của trẻ.

Trong ví dụ sau, ImageButton là _uỷ quyền view_—tức là thành phần con có khu vực 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 hoàn tất các tác vụ này:

  • Lấy chế độ xem 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ẹ sẽ bố trí các phần tử con trước khi gọi phương thức getHitRect() . Phương thức getHitRect() nhận hình chữ nhật lượt truy cập của phần tử con (hoặc vùng có thể chạm) trong toạ độ của phần tử mẹ.
  • Tìm khung hiển thị con ImageButton và gọi getHitRect() để lấy phương thức ranh giới khu vực có thể chạm vào của trẻ.
  • Mở rộng giới hạn hình chữ nhật lượt truy cập của khung hiển thị 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à Chế độ xem con ImageButton dưới dạng tham số.
  • Đặt TouchDelegate trên khung hiển thị mẹ để thao tác chạm trong thực thể uỷ quyền cảm ứng các giới hạn sẽ được định tuyến đến phần tử con.

Với vai trò là uỷ quyền cảm ứng cho khung hiển thị con của ImageButton, khung hiển thị mẹ nhận tất cả cá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, truyền sự kiện chạm đến phần tử 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);
                }
            }
        });
    }
}