Việc xử lý các sự kiện chạm trong a
ViewGroup cần được chú ý đặc biệt
vì ViewGroup thường có các phần tử 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 đúng các sự kiện chạm dành cho khung hiển thị đó, hãy ghi đè phương thức onInterceptTouchEvent().
Hãy tham khảo các tài nguyên liên quan sau:
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 một sự kiện chạm được phát hiện trên bề mặt của ViewGroup, kể cả trên bề mặt của các phần tử con. Nếu onInterceptTouchEvent() trả về true, thì MotionEvent sẽ bị chặn, nghĩa là sự kiện này không được truyền cho phần tử con mà được truyền cho phương thức onTouchEvent() của phần tử mẹ.
Phương thức onInterceptTouchEvent() cho phép phần tử mẹ có cơ hội xem các sự kiện chạm trước khi các phần tử con xem. 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 sẽ được gửi đến phương thức onTouchEvent() của phần tử 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 view đến các mục tiêu thông thường, xử lý các sự kiện bằng onTouchEvent() riê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 theo chiều ngang trên một khung hiển thị con, thì khung hiển thị con đó sẽ không nhận được 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. Tuy nhiên, nếu bạn nhấn vào các nút trong chế độ xem dữ liệu trẻ em hoặc cuộn chế độ xem dữ liệu trẻ em theo chiều dọc, thì phần tử mẹ sẽ không chặn các sự kiện chạm đó vì phần tử con là mục tiêu dự kiến. Trong những trường hợp đó, onInterceptTouchEvent() sẽ trả về false và onTouchEvent() 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 phương thức requestDisallowInterceptTouchEvent(). ViewGroup gọi phương thức này khi một phần tử con không muốn phần tử mẹ và các phần tử tổ tiên của phần tử đó chặn các sự kiện chạm bằng onInterceptTouchEvent().
Xử lý các sự kiện ACTION_OUTSIDE
Nếu ViewGroup nhận được MotionEvent có ACTION_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ý trong
Window.Callback có liên quan, chẳng hạn như 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 thường dùng do hệ thống Android sử dụng.
"Độ trễ khi 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à thao tác cuộn. Độ trễ khi chạm thường được dùng để ngăn thao tá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 thường dùng khác là getScaledMinimumFlingVelocity() và 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 thao tác vuốt được đo bằng pixel trên 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 vùng có thể chạm của khung hiển thị con
Android cung cấp lớp TouchDelegate để cho phép phần tử mẹ mở rộng vùng có thể chạm của khung hiển thị con vượt ra ngoài giới hạn của phần tử con. Điều này hữu ích khi phần tử 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 hẹp vùng chạm của phần tử con.
Trong ví dụ sau, ImageButton là _khung hiển thị uỷ quyền_ , tức là phần tử con có vùng chạm 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 hoàn thành các việc cần làm này:
- Lấy chế độ xem của cha mẹ và đăng
Runnabletrên Luồng giao diện người dùng. Điều này đảm bảo rằng phần tử mẹ bố trí các phần tử con trước khi gọi phương thức.getHitRect()Phương thứcgetHitRect()lấy hình chữ nhật nhấn (hoặc vùng có thể chạm) của phần tử con theo toạ độ của phần tử mẹ. - Tìm khung hiển thị con
ImageButtonvà gọigetHitRect()để lấy giới hạn của vùng có thể chạm của phần tử con. - Mở rộng giới hạn của hình chữ nhật nhấn của khung hiển thị con
ImageButton. - Khởi tạo
TouchDelegate, truyền hình chữ nhật nhấn đã mở rộng vàImageButtonkhung hiển thị con làm tham số. - Đặt
TouchDelegatetrên chế độ xem của cha mẹ để các thao tác chạm trong giới hạn của đại diện chạm được chuyển đến phần tử con.
Với tư cách là người được uỷ quyền chạm cho chế độ xem dữ liệu trẻ em ImageButton, chế độ xem của cha mẹ sẽ 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 phần tử con, thì phần tử mẹ sẽ truyền sự kiện chạm đó cho 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); } } }); } }