O gerenciamento de eventos de toque em um ViewGroup
requer cuidados especiais, porque é comum que um ViewGroup
tenha filhos que sejam destinos de diferentes eventos de toque além do próprio ViewGroup
. Para garantir que cada visualização receba os eventos de toque destinados a ela, modifique o método onInterceptTouchEvent()
.
Confira os seguintes recursos relacionados:
Interceptar eventos de toque em um ViewGroup
O método onInterceptTouchEvent()
é chamado sempre que um evento de toque é detectado na superfície de um ViewGroup
, inclusive na superfície dos próprios filhos. Se onInterceptTouchEvent()
retornar true
, o MotionEvent
será interceptado, ou seja, ele não será transmitido para o filho, mas ao método onTouchEvent()
do pai.
Com o método onInterceptTouchEvent()
, o pai tem a possibilidade de ver qualquer evento de toque antes dos filhos. Se você retornar true
de onInterceptTouchEvent()
, a visualização filha que estava processando os eventos de toque receberá um ACTION_CANCEL
, e os eventos desse ponto em diante serão enviados ao método onTouchEvent()
do pai para o processamento usual.
O onInterceptTouchEvent()
também pode retornar false
e apenas observar os eventos enquanto eles percorrem a hierarquia de visualização até os destinos habituais, que gerenciarão 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 horizontalmente em uma visualização filha, ela não receberá mais eventos de toque, e o MyViewGroup
processará esses eventos rolando o conteúdo. No entanto, se você pressionar botões na visualização filha ou rolar essa visualização verticalmente, o pai não deverá interceptar esses eventos de toque, porque a filha é o destino pretendido. Nesses casos, onInterceptTouchEvent()
retornará false
, e o MyViewGroup
do onTouchEvent()
não será 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 JUST determines whether we want to intercept the motion. * If we return true, onTouchEvent will be called and we 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 // Do not intercept touch event, let the child handle it } MotionEvent.ACTION_MOVE -> { if (mIsScrolling) { // We're currently scrolling, so yes, intercept the // touch event! true } else { // If the user has dragged her finger horizontally more than // the touch slop, start the scroll // left as an exercise for the reader val xDiff: Int = calculateDistanceX(ev) // Touch slop should be calculated using ViewConfiguration // constants. if (xDiff > mTouchSlop) { // Start scrolling! mIsScrolling = true true } else { false } } } ... else -> { // In general, we don't want to intercept touch events. They should be // handled by the child view. false } } } override fun onTouchEvent(event: MotionEvent): Boolean { // Here we actually handle the touch event (e.g. if the action is ACTION_MOVE, // scroll this container). // This method will only be called if the touch event was 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 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; } @Override public boolean onTouchEvent(MotionEvent ev) { // Here we actually handle the touch event (e.g. if the action is ACTION_MOVE, // scroll this container). // This method will only be called if the touch event was intercepted in // onInterceptTouchEvent ... } }
ViewGroup
também fornece um método requestDisallowInterceptTouchEvent()
.
O ViewGroup
chama esse método quando um filho 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 enviá-lo para a View
correta ou processe-o no Window.Callback
relevante (por exemplo, Activity
).
Usar constantes ViewConfiguration
O snippet acima usa a ViewConfiguration
atual para inicializar uma variável denominada mTouchSlop
. Você pode usar a classe ViewConfiguration
para acessar distâncias, velocidades e tempos comuns usados pelo sistema Android.
"Tolerância de toque" refere-se à distância em pixels que o toque do usuário pode percorrer antes que o gesto seja interpretado como rolagem. Normalmente, esse parâmetro é usado para evitar rolagens acidentais quando o usuário está realizando 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 as velocidades mínima e máxima (respectivamente) para iniciar uma movimentação, medidas 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 occurred, do something } return false } ... MotionEvent.ACTION_UP -> { ... if (velocityX in mMinFlingVelocity..mMaxFlingVelocity && velocityY < velocityX) { // The criteria have been 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 occurred, do something } ... case MotionEvent.ACTION_UP: { ... } if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity && velocityY < velocityX) { // The criteria have been satisfied, do something } }
Estender a área de toque de uma visualização filha
O Android disponibiliza a classe TouchDelegate
para permitir que um pai estenda a área de toque de uma visualização filha além dos limites dela.
Esse recurso é útil quando o filho precisa ser pequeno, mas deve ter uma região de toque maior. Você também pode usar essa abordagem para reduzir a região de toque da filha, se necessário.
No exemplo a seguir, um ImageButton
é a "visualização delegada" (ou seja, a filha cuja área de toque o pai expandirá).
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 abaixo faz o seguinte:
- 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étodogetHitRect()
. O métodogetHitRect()
coloca o retângulo ativo da filha (área de toque) nas coordenadas do pai. - Encontra a visualização filha
ImageButton
e chamagetHitRect()
para conseguir os limites da área de toque da filha. - Estende os limites do retângulo ativo de
ImageButton
. - Instancia um
TouchDelegate
, transmitindo o retângulo ativo expandido e a visualização filha deImageButton
como parâmetros. - Define o
TouchDelegate
na visualização pai, de modo que os toques dentro dos limites definidos de toque sejam roteados para a filha.
Na qualidade de delegado de toque para a visualização filha de ImageButton
, a visualização pai receberá todos os eventos de toque. Se o evento de toque ocorrer dentro do retângulo ativo da filha, o pai transmitirá esse evento para que a filha o processe.
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 (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 // Sets the TouchDelegate on the parent view, such 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 should receive 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 (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 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); } } }); } }