Gestire gli eventi di tocco in un ViewGroup

Gestire gli eventi touch in una ViewGroup presta particolare attenzione perché è normale che un ViewGroup abbia elementi secondari target per diversi eventi touch rispetto allo stesso ViewGroup. Per assicurarti che ogni vista riceva correttamente i gli eventi touch previsti, sostituisci onInterceptTouchEvent() .

Intercetta gli eventi di tocco in un ViewGroup

Il metodo onInterceptTouchEvent() viene chiamato ogni volta che viene rilevato un evento tocco sul la superficie di un ViewGroup, inclusa quella dei relativi elementi secondari. Se onInterceptTouchEvent() restituisce true, MotionEvent viene intercettato, vale a dire che non viene trasmesso al file secondario, ma onTouchEvent() del publisher principale.

Il metodo onInterceptTouchEvent() offre a un genitore la possibilità di vedere gli eventi touch prima che lo facciano i figli. Se restituisci true da onInterceptTouchEvent(), la vista secondaria che in precedenza gestiva gli eventi touch riceve ACTION_CANCEL, e gli eventi da quel momento in poi vengono inviati al metodo onTouchEvent() del publisher principale per la normale gestione. onInterceptTouchEvent() può anche restituire false e spiare gli eventi mentre si spostano nella gerarchia di visualizzazione fino ai loro bersagli abituali, che gestiscono eventi con il proprio onTouchEvent().

Nel seguente snippet, la classe MyViewGroup è un'estensione di ViewGroup. MyViewGroup contiene più viste secondarie. Se trascini il dito sulla vista bambino in orizzontale, la vista bambino non riceve più gli eventi tocco e MyViewGroup gestisce il tocco facendo scorrere i contenuti. Tuttavia, se tocchi i pulsanti nella vista bambino o fai scorrere il riquadro vista verticale, l'elemento principale non intercetta questi eventi touch perché l'elemento secondario è l'oggetto target. In questi casi, onInterceptTouchEvent() restituisce false e la macro onTouchEvent() del corso MyViewGroup non viene chiamato.

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

Tieni presente che ViewGroup fornisce anche una requestDisallowInterceptTouchEvent() . L'ViewGroup chiama questo metodo quando un publisher secondario non vuole l'elemento principale e i relativi predecessori per intercettare gli eventi touch con onInterceptTouchEvent().

Elabora eventi ACTION_OUTSIDE

Se ViewGroup riceve un MotionEvent con un ACTION_OUTSIDE, l'evento non viene inviato ai relativi figli per impostazione predefinita. Per elaborare un MotionEvent con ACTION_OUTSIDE, entrambi gli override dispatchTouchEvent(MotionEvent event) da inviare al View o gestirla nel relativo Window.Callback—per ad esempio Activity.

Usa costanti ViewConfiguration

Lo snippet precedente utilizza il valore ViewConfiguration corrente per inizializzare una variabile chiamato mTouchSlop. Puoi utilizzare il corso ViewConfiguration per accedere distanze, velocità e tempi comuni utilizzati dal sistema Android.

"Touch slop" indica la distanza in pixel in cui l'utente deve camminare con il tocco prima che venga eseguito il gesto interpretata come scorrimento. L'inclinazione al tocco viene generalmente utilizzata per impedire lo scorrimento accidentale quando l'utente sta eseguendo un'altra operazione touch, ad esempio toccare elementi sullo schermo.

Altri due metodi di ViewConfiguration comunemente utilizzati sono getScaledMinimumFlingVelocity() e getScaledMaximumFlingVelocity(). Questi metodi restituiscono rispettivamente la velocità minima e massima per avviare un fling misurato in pixel al secondo. Ad esempio:

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

Estendi l'area toccabile di una vista bambino

Android offre TouchDelegate corso per partecipare un genitore può estendere l'area toccabile di una vista secondaria oltre i suoi limiti. Questo è utile quando il bambino deve essere piccolo ma ha bisogno di una zona tattile più ampia. Puoi usare anche questo per rimpicciolire la regione del tocco del bambino.

Nell'esempio seguente, ImageButton è il _delegate view_, ovvero il riquadro secondario di cui estende l'area di tocco del genitore. Ecco il file di layout:

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

Il seguente snippet completa queste attività:

  • Ottiene la vista genitore e pubblica un Runnable nel thread dell'interfaccia utente. In questo modo ti assicuri che il publisher principale impagina i file secondari prima di chiamare il metodo getHitRect() . Il metodo getHitRect() ottiene il rettangolo hit del figlio (o area toccabile) nelle coordinate del genitore.
  • Trova la vista figlio ImageButton e chiama getHitRect() per ottenere limiti dell'area toccabile del bambino.
  • Estende i limiti del rettangolo dell'hit della vista secondaria ImageButton.
  • Crea un'istanza per un TouchDelegate, passando per il rettangolo a scorrimento espanso e ImageButton vista secondaria come parametri.
  • Imposta TouchDelegate nella vista genitore in modo che tocchi all'interno del delegato al tocco vengono indirizzati all'account figlio.

In qualità di delegato al tocco per la vista secondaria ImageButton, la vista genitore riceve tutti gli eventi touch. Se l'evento tocco si verifica all'interno del rettangolo di selezione del publisher secondario, il publisher principale passa l'evento tocco al componente secondario per la gestione.

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