Gerenciar eventos de toque em um ViewGroup

O processamento de eventos de toque em uma ViewGroup toma cuidado especial, porque é comum que uma ViewGroup tenha filhos que sejam alvos de eventos de toque diferentes da ViewGroup. Para garantir que cada visualização receba os eventos de toque destinados a ela, modifique o método onInterceptTouchEvent().

Interceptar eventos de toque em um ViewGroup

O método onInterceptTouchEvent() é chamado sempre que um evento de toque é detectado na superfície de uma ViewGroup, inclusive na superfície dos filhos. Se onInterceptTouchEvent() retornar true, o MotionEvent será interceptado, o que significa que ele não será transmitido para o filho, mas para o método onTouchEvent() do pai.

O método onInterceptTouchEvent() dá ao pai a chance de ver eventos de toque antes que os filhos façam isso. Se você retornar true de onInterceptTouchEvent(), a visualização filha que processava eventos de toque anteriormente vai receber um ACTION_CANCEL, e os eventos desse ponto em diante serão enviados ao método onTouchEvent() do pai para o processamento normal. onInterceptTouchEvent() também pode retornar false e espionar os eventos enquanto percorrem a hierarquia de visualização até os destinos habituais, que processam os eventos com o próprio onTouchEvent().

No snippet a seguir, a classe MyViewGroup estende ViewGroup. MyViewGroup contém várias visualizações filhas. Se você arrastar o dedo na horizontal por uma visualização filha, ela não vai mais receber eventos de toque, e o MyViewGroup vai processar esses eventos rolando o conteúdo. No entanto, se você tocar em botões na visualização filha ou rolar a visualização filha verticalmente, o pai não vai interceptar esses eventos de toque, porque a filha é o destino pretendido. Nesses casos, onInterceptTouchEvent() retorna false e o onTouchEvent() da classe MyViewGroup não é chamado.

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

Observe que ViewGroup também fornece um método requestDisallowInterceptTouchEvent(). O ViewGroup chama esse método quando uma filha não quer que o pai e os ancestrais interceptem eventos de toque com onInterceptTouchEvent().

Processar eventos ACTION_OUTSIDE

Se um ViewGroup receber um MotionEvent com um ACTION_OUTSIDE, o evento não será enviado para os filhos por padrão. Para processar um MotionEvent com ACTION_OUTSIDE, substitua dispatchTouchEvent(MotionEvent event) para o enviar ao View apropriado ou processe-o no Window.Callback relevante, por exemplo, Activity.

Usar constantes ViewConfiguration

O snippet anterior usa o ViewConfiguration atual para inicializar uma variável chamada mTouchSlop. Você pode usar a classe ViewConfiguration para acessar distâncias, velocidades e tempos comuns usados pelo sistema Android.

"Tolerância de toque" se refere à distância em pixels que o toque do usuário pode percorrer antes que o gesto seja interpretado como rolagem. A tolerância de toque normalmente é usada para evitar rolagem acidental quando o usuário realiza outra operação de toque, como tocar em elementos na tela.

Dois outros métodos ViewConfiguration mais usados são getScaledMinimumFlingVelocity() e getScaledMaximumFlingVelocity(). Esses métodos retornam a velocidade mínima e máxima, respectivamente, para iniciar uma movimentação medida em pixels por segundo. Por exemplo:

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

Estender a área de toque de uma visualização filha

O Android oferece a classe TouchDelegate para possibilitar que um pai estenda a área de toque de uma visualização filha além dos limites dela. Isso é útil quando o filho precisa ser pequeno, mas precisa de uma região de toque maior. Você também pode usar essa abordagem para reduzir a região de toque da filha.

No exemplo abaixo, um ImageButton é a _visualização delegada_, ou seja, a filha com área de toque estendida pelo pai. Este é o arquivo de 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>

O snippet a seguir conclui essas tarefas:

  • Recebe a visualização pai e publica um Runnable na linha de execução de IU. Isso garante que o pai disponha as próprias filhas antes de chamar o método getHitRect(). O método getHitRect() recebe o retângulo de hit da filha (ou área de toque) nas coordenadas do pai.
  • Encontra a visualização filha ImageButton e chama getHitRect() para definir os limites da área de toque da filha.
  • Estende os limites do retângulo ativo da visualização filha ImageButton.
  • Instancia um TouchDelegate, transmitindo o retângulo ativo expandido e a visualização filha ImageButton como parâmetros.
  • Define o TouchDelegate na visualização pai para que os toques dentro dos limites da delegação de toque sejam roteados para a filha.

Na qualidade de delegado de toque para a visualização filha ImageButton, a visualização mãe recebe todos os eventos de toque. Se o evento de toque ocorrer dentro do retângulo ativo da filha, o pai vai transmitir o evento de toque ao filho para processamento.

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