Cómo administrar eventos táctiles en un ViewGroup

Cómo controlar eventos táctiles en un ViewGroup tiene un cuidado especial ya que es común que un ViewGroup tenga hijos que se destinan a diferentes eventos táctiles que el ViewGroup en sí. Para asegurarte de que cada vista reciba correctamente el eventos táctiles destinados a ella, anulan la onInterceptTouchEvent() .

Como interceptar eventos táctiles en un ViewGroup

Se llama al método onInterceptTouchEvent() cada vez que se detecta un evento táctil en la superficie de un ViewGroup, incluso en la superficie de sus elementos secundarios Si onInterceptTouchEvent() muestra true, el MotionEvent se intercepta, lo que significa que no se pasa al elemento secundario, sino al onTouchEvent() de la clase superior.

El método onInterceptTouchEvent() le da a tu madre o padre la oportunidad de ver eventos táctiles antes que sus hijos. Si devuelves true desde onInterceptTouchEvent(), la vista secundaria que antes controlaba eventos táctiles recibe un ACTION_CANCEL, A partir de ese momento, los eventos se envían al método onTouchEvent() del elemento superior para el manejo habitual. onInterceptTouchEvent() también puede mostrar false y espiar a los eventos mientras pasan por la jerarquía de vistas hacia sus objetivos habituales, que controlan el eventos con su propio onTouchEvent().

En el siguiente fragmento, la clase MyViewGroup extiende ViewGroup. MyViewGroup contiene varias vistas secundarias. Si arrastras el dedo por una vista secundaria horizontalmente, la vista secundaria ya no recibe eventos táctiles, y MyViewGroup controla los controles táctiles de objetos adicionales desplazando su contenido. Sin embargo, si presionas botones en la vista secundaria o desplazas al niño vertical, el elemento superior no intercepta esos eventos táctiles porque el elemento secundario es objetivo. En esos casos, onInterceptTouchEvent() muestra false, y el No se llama al onTouchEvent() de la clase MyViewGroup.

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

Ten en cuenta que ViewGroup también proporciona un requestDisallowInterceptTouchEvent() . El ViewGroup llama a este método cuando un elemento secundario no quiere que el elemento superior y su principales para interceptar eventos táctiles con onInterceptTouchEvent()

Cómo procesar eventos ACTION_OUTSIDE

Si un objeto ViewGroup recibe un objeto MotionEvent con una ACTION_OUTSIDE, el evento no se envía a sus elementos secundarios de forma predeterminada. Para procesar un MotionEvent con ACTION_OUTSIDE, cualquiera de las anulaciones dispatchTouchEvent(MotionEvent event) para enviarlos al View adecuado o abordarlo con los Window.Callback durante por ejemplo, Activity.

Cómo usar las constantes de ViewConfiguration

En el fragmento anterior, se usa el ViewConfiguration actual para inicializar una variable llamada mTouchSlop. Puedes usar la clase ViewConfiguration para acceder las distancias, las velocidades y los tiempos comunes que usa el sistema Android.

"Inclinación táctil" se refiere a la distancia en píxeles en que el tacto de un usuario puede oscilar antes de que se realice el gesto se interpretan como desplazamiento. Por lo general, se usa el margen táctil para evitar el desplazamiento accidental cuando el usuario realiza otra operación táctil, como tocar elementos en pantalla.

Otros dos métodos ViewConfiguration de uso general son getScaledMinimumFlingVelocity() y getScaledMaximumFlingVelocity() Estos métodos devuelven las velocidades mínima y máxima, respectivamente, para iniciar un lanzamiento medido en píxeles por segundo. Por ejemplo:

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

Cómo extender el área táctil de una vista secundaria

Android proporciona la TouchDelegate clase para que sea posible que un elemento superior extienda el área táctil de una vista secundaria más allá de los límites del elemento secundario. Esta Resulta útil cuando el elemento secundario debe ser pequeño, pero necesita una región táctil más grande. También puedes usar para reducir la región táctil del elemento secundario.

En el siguiente ejemplo, se ImageButton es _delegate. view_, es decir, el elemento secundario cuya área táctil extiende el elemento superior. Aquí puedes ver el archivo de diseño:

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

El siguiente fragmento completa estas tareas:

  • Obtiene la vista superior y publica un Runnable en el subproceso de IU. Esto garantiza que el padre disponga sus elementos secundarios antes de llamar al getHitRect() . El método getHitRect() obtiene el rectángulo de acceso del elemento secundario (o área táctil) en las coordenadas del elemento superior.
  • Busca la vista secundaria ImageButton y llama a getHitRect() para obtener lo siguiente: límites del área táctil del niño.
  • Extiende los límites del rectángulo de visita de la vista secundaria ImageButton.
  • Crea una instancia de TouchDelegate y pasa el rectángulo de visita expandido y el Vista secundaria de ImageButton como parámetros.
  • Establece el objeto TouchDelegate en la vista superior para que toque dentro del delegado táctil. límites se enrutan al elemento secundario.

En su calidad de delegado táctil para la vista secundaria ImageButton, la vista superior recibe todos los eventos táctiles. Si el evento táctil ocurre dentro del rectángulo de visita del elemento secundario, pasa el evento táctil al elemento secundario para que lo controle.

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