2011-09-12 14 views
8

Ho una vista personalizzata che si comporta come un pulsante. Voglio cambiare lo sfondo quando l'utente lo preme, ripristinare lo sfondo originale quando l'utente sposta il dito all'esterno o rilasciarlo e voglio anche gestire gli eventi onClick/onLongClick. Il problema è che onTouch richiede che restituisca true per ACTION_DOWN o che non mi invii l'evento ACTION_UP. Ma se restituisco true il listener onClick non funzionerà.Android onTouch con onClick e onLongClick

Pensavo di averlo risolto restituendo false in onTouch e registrando onClick - in qualche modo funzionava, ma era un po 'contro i documenti. Ho appena ricevuto un messaggio da un utente che mi ha detto che non è in grado di fare un clic prolungato sul pulsante, quindi mi sto chiedendo cosa c'è che non va.

Parte del codice corrente:

public boolean onTouch(View v, MotionEvent evt) 
{ 
    switch (evt.getAction()) 
    { 
    case MotionEvent.ACTION_DOWN: 
    { 
     setSelection(true); // it just change the background 
     break; 
    } 

    case MotionEvent.ACTION_CANCEL: 
    case MotionEvent.ACTION_UP: 
    case MotionEvent.ACTION_OUTSIDE: 
    { 
     setSelection(false); // it just change the background 
     break; 
    } 
    } 

    return false; 
} 

public void onClick(View v) 
{ 
    // some other code here 
} 

public boolean onLongClick(View view) 
    { 
    // just showing a Toast here 
    return false; 
    } 


// somewhere else in code 
setOnTouchListener(this); 
setOnClickListener(this); 
setOnLongClickListener(this); 

Come faccio farli lavorare insieme in modo corretto?

Grazie in anticipo

risposta

10

onClick & onLongClick è in realtà spediti dal View.onTouchEvent.

se si ignora View.onTouchEvent o impostare alcune specifiche View.OnTouchListener via setOnTouchListener, è necessario prendersi cura di questo.

modo che il codice dovrebbe essere qualcosa di simile:

 
public boolean onTouch(View v, MotionEvent evt) 
{ 
    // to dispatch click/long click event, 
    // you must pass the event to it's default callback View.onTouchEvent 
    boolean defaultResult = v.onTouchEvent(evt); 

    switch (evt.getAction()) 
    { 
    case MotionEvent.ACTION_DOWN: 
    { 
     setSelection(true); // just changing the background 
     break; 
    } 
    case MotionEvent.ACTION_CANCEL: 
    case MotionEvent.ACTION_UP: 
    case MotionEvent.ACTION_OUTSIDE: 
    { 
     setSelection(false); // just changing the background 
     break; 
    } 
    default: 
     return defaultResult; 
    } 

    // if you reach here, you have consumed the event 
    return true; 
} 
Problemi correlati