Buscar..


Cómo variar entre los eventos táctiles de grupo de vista infantil y padre

  1. onTouchEvents() para grupos de vistas anidadas se puede administrar mediante el boolean onInterceptTouchEvent .

El valor predeterminado para OnInterceptTouchEvent es falso.

onTouchEvent los onTouchEvent se recibe antes que el niño. Si OnInterceptTouchEvent devuelve false, envía el evento de movimiento a lo largo de la cadena al controlador OnTouchEvent del niño. Si retorna verdadero, los padres manejarán el evento táctil.

Sin embargo, puede haber casos en los que deseamos que algunos elementos secundarios gestionen los OnTouchEvent de OnTouchEvent y otros que sean gestionados por la vista principal (o posiblemente el principal del elemento primario).

Esto se puede gestionar de más de una manera.

  1. Una forma en que un elemento secundario se puede proteger de OnInterceptTouchEvent del OnInterceptTouchEvent es mediante la implementación del requestDisallowInterceptTouchEvent .

public void requestDisallowInterceptTouchEvent (boolean disallowIntercept)

Esto evita que cualquiera de las vistas principales administre OnTouchEvent para este elemento, si el elemento tiene habilitados los controladores de eventos.

Si OnInterceptTouchEvent es falso, se evaluará OnTouchEvent del elemento OnTouchEvent . Si tiene métodos dentro de los elementos secundarios que manejan los diversos eventos táctiles, cualquier controlador de eventos relacionado que esté deshabilitado devolverá el OnTouchEvent al padre.

Esta respuesta:
Una visualización de cómo la propagación de eventos táctiles pasa a través de:
parent -> child|parent -> child|parent -> child views.

introduzca la descripción de la imagen aquí Cortesía desde aquí

  1. Otra forma es devolver valores variables de OnInterceptTouchEvent para el padre.

Este ejemplo, tomado de Managing Touch Events en un ViewGroup, demuestra cómo interceptar el OnTouchEvent del niño cuando el usuario se desplaza.

4a.

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

Este es un código del mismo enlace que muestra cómo crear los parámetros del rectángulo alrededor de su elemento:

4b.

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


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow