ViewGroup'taki dokunma etkinliklerini yönetme

Compose yöntemini deneyin
Jetpack Compose, Android için önerilen kullanıcı arayüzü araç setidir. Compose'daki hareketler hakkında bilgi edinin.

ViewGroup içinde dokunma etkinliklerini işlerken özel dikkat göstermeniz gerekir. Çünkü ViewGroup içinde, ViewGroup'nin kendisinden farklı dokunma etkinliklerini hedefleyen alt öğeler olması yaygındır. Her görünümün, kendisine yönelik dokunma etkinliklerini doğru şekilde aldığından emin olmak için onInterceptTouchEvent() yöntemini geçersiz kılın.

ViewGroup'taki dokunma etkinliklerini yakalama

onInterceptTouchEvent() yöntemi, alt öğelerinin yüzeyi de dahil olmak üzere ViewGroup yüzeyinde dokunma etkinliği algılandığında çağrılır. onInterceptTouchEvent() true değerini döndürürse MotionEvent yakalanır. Yani çocuğa değil, üst öğenin onTouchEvent() yöntemine iletilir.

onInterceptTouchEvent() yöntemi, ebeveynlere dokunma etkinliklerini çocuklarından önce görme fırsatı verir. onInterceptTouchEvent() yönteminden true döndürürseniz dokunma etkinliklerini daha önce işleyen alt görünüm bir ACTION_CANCEL alır ve o noktadan sonraki etkinlikler, normal işleme için ebeveynin onTouchEvent() yöntemine gönderilir. onInterceptTouchEvent(), false değerini de döndürebilir ve etkinlikler, kendi onTouchEvent() ile etkinlikleri işleyen normal hedeflerine doğru görünüm hiyerarşisinde ilerlerken etkinlikleri izleyebilir.

Aşağıdaki snippet'te MyViewGroup sınıfı, ViewGroup sınıfını genişletir. MyViewGroup birden fazla alt görünüm içeriyor. Parmaklarınızı bir çocuk ekranında yatay olarak kaydırdığınızda çocuk ekranı artık dokunma etkinliklerini almaz ve MyViewGroup, içeriklerini kaydırarak dokunma etkinliklerini işler. Ancak çocuk ekranındaki düğmelere dokunursanız veya alt görünümü dikey olarak kaydırırsanız üst öğe, amaçlanan hedef alt öğe olduğundan bu dokunma etkinliklerini yakalamaz. Bu gibi durumlarda onInterceptTouchEvent(), false değerini döndürür ve MyViewGroup sınıfının onTouchEvent() işlevi çağrılmaz.

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

ViewGroup öğesinin requestDisallowInterceptTouchEvent() yöntemi de sağladığını unutmayın. ViewGroup, alt öğe, üst öğenin ve üst öğenin atalarının onInterceptTouchEvent() ile dokunma etkinliklerini engellemesini istemediğinde bu yöntemi çağırır.

ACTION_OUTSIDE etkinliklerini işleme

Bir ViewGroup, ACTION_OUTSIDE içeren bir MotionEvent alırsa etkinlik varsayılan olarak alt öğelerine gönderilmez. MotionEvent ile ACTION_OUTSIDE işlemek için dispatchTouchEvent(MotionEvent event)'yi geçersiz kılarak uygun View'e gönderebilir veya ilgili Window.Callback'de (ör. Activity) işleyebilirsiniz.

ViewConfiguration sabitlerini kullanma

Önceki snippet, ViewConfiguration adlı bir değişkeni başlatmak için geçerli mTouchSlop değerini kullanır. Android sistemi tarafından kullanılan ortak mesafelere, hızlara ve zamanlara erişmek için ViewConfiguration sınıfını kullanabilirsiniz.

"Dokunma hatası", kullanıcının dokunuşunun kaydırma hareketi olarak yorumlanmadan önce kaç piksel hareket edebileceğini ifade eder. Dokunma eğimi, kullanıcı ekrandaki öğelere dokunma gibi başka bir dokunma işlemi yaparken yanlışlıkla kaydırmayı önlemek için genellikle kullanılır.

Yaygın olarak kullanılan diğer iki ViewConfiguration yöntemi ise getScaledMinimumFlingVelocity() ve getScaledMaximumFlingVelocity()'dir. Bu yöntemler, sırasıyla saniyede piksel cinsinden ölçülen bir hızlı kaydırma başlatmak için minimum ve maksimum hızı döndürür. Örneğin:

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

Çocuk görünümünün dokunulabilir alanını genişletme

Android, ebeveynlerin dokunulabilir alanı alt görünümün sınırlarının ötesine genişletmesini sağlamak için TouchDelegate sınıfını sağlar. Bu, çocuğun küçük olması gerektiğinde ancak daha büyük bir dokunma bölgesine ihtiyaç duyduğunda kullanışlıdır. Bu yaklaşımı, çocuğun dokunma bölgesini küçültmek için de kullanabilirsiniz.

Aşağıdaki örnekte, ImageButton, _delegate view_ yani dokunma alanını üst öğenin genişlettiği alt öğedir. Düzen dosyası:

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

Aşağıdaki snippet bu görevleri tamamlar:

  • Ebeveyn görünümünü alır ve kullanıcı arayüzü iş parçacığına Runnable gönderir. Bu, ebeveynin getHitRect() yöntemini çağırmadan önce çocuklarını yerleştirmesini sağlar. getHitRect() yöntemi, ebeveynin koordinatlarında çocuğun dokunma dikdörtgenini (veya dokunulabilir alanı) alır.
  • ImageButton alt öğe görünümünü bulur ve getHitRect() çağrısı yaparak alt öğenin dokunulabilir alanının sınırlarını alır.
  • ImageButton alt görünümünün dokunma dikdörtgeninin sınırlarını genişletir.
  • Genişletilmiş isabet dikdörtgenini ve ImageButton çocuk ekranını parametre olarak ileterek TouchDelegate öğesini oluşturur.
  • Dokunma temsilcisi sınırları içindeki dokunmaların alt öğeye yönlendirilmesi için ebeveyn görünümünde TouchDelegate ayarlanır.

Üst görünüm, ImageButtonalt görünümün dokunma temsilcisi olarak tüm dokunma etkinliklerini alır. Dokunma etkinliği alt öğenin dokunma dikdörtgeni içinde gerçekleşirse üst öğe, dokunma etkinliğini işlenmesi için alt öğeye iletir.

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