2012-01-13 5 views
124

Quiero agregar OnLongClickListener en mi vista de lista. Cada vez que el usuario presiona el elemento en la lista, se debe realizar alguna acción, pero mi código no capta a este oyente. Por favor, hágame saber dónde me estoy equivocando. El código similar funciona muy bien para setOnItemClickListener.cómo implementar un detector de clics largo en una vista de lista

Aquí está el código:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 

      public boolean onItemLongClick(AdapterView<?> arg0, View v, 
        int index, long arg3) { 
       // TODO Auto-generated method stub 
       Log.d("in onLongClick"); 
       String str=listView.getItemAtPosition(index).toString(); 

       Log.d("long click : " +str); 
       return true; 
      } 
}); 
+0

ver en xml si el clic largo está habilitado? –

+0

¿Se acordó de agregar "implementa OnItemLongClickListener" a su declaración de clase? – barry

+0

Tal vez tengas un Escucha de gestos o algo así que está capturando la presión prolongada y consumiéndolo. –

Respuesta

281

usted tiene que fijar setOnItemLongClickListener() en el ListView:

lv.setOnItemLongClickListener(new OnItemLongClickListener() { 
      @Override 
      public boolean onItemLongClick(AdapterView<?> arg0, View arg1, 
        int pos, long id) { 
       // TODO Auto-generated method stub 

       Log.v("long clicked","pos: " + pos); 

       return true; 
      } 
     }); 

El XML para cada elemento de la lista (en caso de que utilice un XML personalizado) debe tener android:longClickable="true" también (o puede utilizar el método de conveniencia lv.setLongClickable(true);). De esta forma, puede tener una lista con solo algunos elementos que responden a longclick.

Espero que esto te ayude.

+21

Asegúrese de llamar a 'lv.setLongClickable (true);' también. –

+14

Esto no funcionó para mí. Pero esto hace: 'lv.setOnItemLongClickListener (nuevo AdapterView.OnItemLongClickListener() {...' –

+0

de alguna manera, adroid: longClickable = "true" es el predeterminado. Estoy usando API 19. Así que no tuve que especificarlo en absoluto . – user1592714

5

Creo que el código anterior funcionará en LongClicking la vista de lista, no los elementos individuales.

por qué no usar registerForContextMenu(listView). y luego obtener la devolución de llamada en OnCreateContextMenu.

Para la mayoría de los casos, esto funcionará igual.

13

o probar este código:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 

      public boolean onItemLongClick(AdapterView<?> arg0, View v, 
        int index, long arg3) { 

    Toast.makeText(list.this,myList.getItemAtPosition(index).toString(), Toast.LENGTH_LONG).show(); 
       return false; 
      } 
}); 
18

Si su ListView fila elemento hace referencia a un archivo XML independiente, asegúrese de agregar android:longClickable="true" a ese archivo de diseño además de fijar setOnItemLongClickListener() a su ListView.

+0

¡Gracias! Me estaba golpeando la cabeza con este. – Shaihi

0

esto debería funcionar

ListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 

      @Override 
      public boolean onItemLongClick(AdapterView<?> arg0, View arg1, 
              int pos, long id) { 
       // TODO Auto-generated method stub 

       Toast.makeText(getContext(), "long clicked, "+"pos: " + pos, Toast.LENGTH_LONG).show(); 

       return true; 
      } 
     }); 

también no se olvide de su xml android:longClickable="true" o si tiene una vista personalizada añadir esto a la vista personalizada clase youCustomView.setLongClickable(true);

aquí es la salida del código arriba enter image description here

0

He probado la mayoría de estas respuestas y todas ellas fallaban para TextViews que tenían habilitado el enlace automático pero también tenían que presionar prolongadamente en el mismo lugar.

Hice una clase personalizada que funciona.

public class TextViewLinkLongPressUrl extends TextView { 

    private boolean isLongClick = false; 

    public TextViewLinkLongPressUrl(Context context) { 
     super(context); 
    } 

    public TextViewLinkLongPressUrl(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public TextViewLinkLongPressUrl(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
    } 

    @Override 
    public void setText(CharSequence text, BufferType type) { 
     super.setText(text, type); 
    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 

     if (event.getAction() == MotionEvent.ACTION_UP && isLongClick) { 
      isLongClick = false; 
      return false; 
     } 

     if (event.getAction() == MotionEvent.ACTION_UP) { 
      isLongClick = false; 
     } 

     if (event.getAction() == MotionEvent.ACTION_DOWN) { 
      isLongClick = false; 
     } 

     return super.onTouchEvent(event); 
    } 

    @Override 
    public boolean performLongClick() { 
     isLongClick = true; 
     return super.performLongClick(); 
    } 
} 
Cuestiones relacionadas