Penanganan peristiwa sentuh dalam ViewGroup
membutuhkan perhatian khusus, karena merupakan hal yang umum bagi ViewGroup
untuk memiliki turunan yang menjadi target berbagai peristiwa sentuh yang berbeda dari ViewGroup
itu sendiri. Untuk memastikan bahwa setiap tampilan menerima peristiwa sentuh yang ditujukan untuknya dengan benar, ganti metode onInterceptTouchEvent()
.
Lihat referensi terkait berikut:
Mencegat peristiwa sentuh di ViewGroup
Metode onInterceptTouchEvent()
dipanggil setiap kali peristiwa sentuh terdeteksi di permukaan ViewGroup
, termasuk di permukaan turunannya. Jika onInterceptTouchEvent()
menampilkan nilai true
, MotionEvent
akan dicegat, yang berarti tidak akan diteruskan ke turunan, melainkan ke metode onTouchEvent()
dari induk.
Metode onInterceptTouchEvent()
memberi kesempatan pada induk untuk melihat adanya peristiwa sentuh apa pun sebelum turunannya. Jika Anda menampilkan nilai true
dari onInterceptTouchEvent()
, tampilan turunan yang sebelumnya menangani peristiwa sentuh akan menerima ACTION_CANCEL
, dan peristiwa sejak waktu tersebut akan dikirim ke metode onTouchEvent()
induk untuk penanganan biasa.
onInterceptTouchEvent()
juga dapat menampilkan false
dan hanya mengintai peristiwa saat menuruni hierarki tampilan ke target biasa, yang kemudian akan menangani peristiwa dengan onTouchEvent()
miliknya.
Dalam cuplikan berikut, class MyViewGroup
meluaskan ViewGroup
.
MyViewGroup
berisi beberapa tampilan turunan. Jika Anda menarik jari di atas tampilan turunan secara horizontal, tampilan turunan seharusnya tidak lagi menerima peristiwa sentuh, dan MyViewGroup
seharusnya menangani peristiwa sentuh dengan men-scroll kontennya. Namun, jika Anda menekan tombol dalam tampilan turunan, atau men-scroll tampilan turunan secara vertikal, induk seharusnya tidak mencegat peristiwa sentuh tersebut, karena turunan adalah target yang dituju. Dalam kasus tersebut, onInterceptTouchEvent()
seharusnya menampilkan false
, dan onTouchEvent()
MyViewGroup
tidak akan dipanggil.
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 JUST determines whether we want to intercept the motion. * If we return true, onTouchEvent will be called and we 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 // Do not intercept touch event, let the child handle it } MotionEvent.ACTION_MOVE -> { if (mIsScrolling) { // We're currently scrolling, so yes, intercept the // touch event! true } else { // If the user has dragged her finger horizontally more than // the touch slop, start the scroll // left as an exercise for the reader val xDiff: Int = calculateDistanceX(ev) // Touch slop should be calculated using ViewConfiguration // constants. if (xDiff > mTouchSlop) { // Start scrolling! mIsScrolling = true true } else { false } } } ... else -> { // In general, we don't want to intercept touch events. They should be // handled by the child view. false } } } override fun onTouchEvent(event: MotionEvent): Boolean { // Here we actually handle the touch event (e.g. if the action is ACTION_MOVE, // scroll this container). // This method will only be called if the touch event was 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 JUST determines whether we want to intercept the motion. * If we return true, onTouchEvent will be called and we 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; // Do not intercept touch event, let the child handle it } switch (action) { case MotionEvent.ACTION_MOVE: { if (mIsScrolling) { // We're currently scrolling, so yes, intercept the // touch event! return true; } // If the user has dragged her finger horizontally more than // the touch slop, start the scroll // left as an exercise for the reader final int xDiff = calculateDistanceX(ev); // Touch slop should be calculated using ViewConfiguration // constants. if (xDiff > mTouchSlop) { // Start scrolling! mIsScrolling = true; return true; } break; } ... } // In general, we don't want to intercept touch events. They should be // handled by the child view. return false; } @Override public boolean onTouchEvent(MotionEvent ev) { // Here we actually handle the touch event (e.g. if the action is ACTION_MOVE, // scroll this container). // This method will only be called if the touch event was intercepted in // onInterceptTouchEvent ... } }
Perlu diingat bahwa ViewGroup
juga menyediakan metode requestDisallowInterceptTouchEvent()
.
ViewGroup
memanggil metode ini ketika suatu turunan tidak menginginkan induk dan ancestornya mencegat peristiwa sentuh dengan onInterceptTouchEvent()
.
Memproses peristiwa ACTION_OUTSIDE
Jika ViewGroup
menerima MotionEvent
dengan ACTION_OUTSIDE
, peristiwa tersebut tidak akan dikirim ke turunannya secara default. Untuk memproses MotionEvent
dengan ACTION_OUTSIDE
, ganti dispatchTouchEvent(MotionEvent event)
untuk dikirim ke View
yang sesuai, atau tangani di Window.Callback
yang relevan (misalnya, Activity
).
Menggunakan konstanta ViewConfiguration
Cuplikan di atas menggunakan ViewConfiguration
saat ini untuk melakukan inisialisasi variabel yang disebut mTouchSlop
. Anda bisa menggunakan class ViewConfiguration
untuk mengakses jarak, kecepatan, dan waktu yang umum digunakan oleh sistem Android.
"Touch slop" merujuk pada jarak dalam piksel yang dapat ditelusuri dengan sentuhan pengguna sebelum gestur diartikan sebagai men-scroll. Touch slop biasanya digunakan untuk mencegah scroll yang tidak disengaja saat pengguna melakukan beberapa operasi sentuhan lainnya, seperti menyentuh elemen di layar.
Dua metode ViewConfiguration
yang umum digunakan adalah getScaledMinimumFlingVelocity()
dan getScaledMaximumFlingVelocity()
.
Metode ini mengembalikan kecepatan minimum dan maksimum (masing-masing) untuk memulai lemparan, sebagaimana yang diukur dalam piksel per detik. Contoh:
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 occurred, do something } return false } ... MotionEvent.ACTION_UP -> { ... if (velocityX in mMinFlingVelocity..mMaxFlingVelocity && velocityY < velocityX) { // The criteria have been 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 occurred, do something } ... case MotionEvent.ACTION_UP: { ... } if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity && velocityY < velocityX) { // The criteria have been satisfied, do something } }
Memperluas area yang dapat disentuh dari tampilan turunan
Android menyediakan class TouchDelegate
untuk memungkinkan induk memperluas area yang dapat disentuh dari tampilan turunan di luar batas turunan.
Hal ini berguna ketika turunan harus berukuran kecil, tetapi memerlukan wilayah sentuhan yang besar. Anda juga dapat menggunakan pendekatan ini untuk memperkecil wilayah sentuhan turunan bila perlu.
Pada contoh berikut, ImageButton
adalah "tampilan delegasi" (yaitu, turunan yang wilayah sentuhannya akan diperluas oleh induk).
Berikut adalah file tata letaknya:
<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>
Cuplikan di bawah ini akan melakukan hal berikut:
- Mendapatkan tampilan induk dan memposting
Runnable
di UI thread. Hal ini akan memastikan bahwa induk akan membuatkan tata letak untuk turunannya sebelum memanggil metodegetHitRect()
. MetodegetHitRect()
membuat kotak klik turunan (area yang dapat disentuh) dalam koordinat induk. - Menemukan tampilan turunan
ImageButton
dan memanggilgetHitRect()
untuk mendapatkan batasan area yang dapat disentuh turunan. - Memperluas batas kotak klik
ImageButton
. - Membuat instance suatu
TouchDelegate
, yang meneruskan kotak klik yang diperluas dan tampilan turunanImageButton
sebagai parameter. - Menyetel
TouchDelegate
pada tampilan induk, sehingga sentuhan dalam batas delegasi sentuh dialihkan ke turunan.
Dalam kapasitasnya sebagai delegasi sentuh untuk tampilan turunan ImageButton
, tampilan induk akan menerima semua peristiwa sentuh. Jika peristiwa sentuh terjadi dalam kotak klik turunan, induknya akan meneruskan peristiwa sentuh tersebut kepada turunan untuk ditangani.
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 (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 // Sets the TouchDelegate on the parent view, such 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 should receive 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 (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 should receive motion // events. TouchDelegate touchDelegate = new TouchDelegate(delegateArea, myButton); // Sets the TouchDelegate on the parent view, such that touches // within the touch delegate bounds are routed to the child. if (View.class.isInstance(myButton.getParent())) { ((View) myButton.getParent()).setTouchDelegate(touchDelegate); } } }); } }