5

¿Cómo puedo configurar la animación cuando el usuario selecciona un elemento en una vista de lista?Android ListView Seleccionar animación

Estoy haciendo mi propio adaptador listview para establecer filas pares con un fondo rosado y filas impares con un fondo morado. El único problema es que no estoy seguro de cómo configurar la animación para que el usuario haga clic ("tocar") un elemento.

Pensé en implementar OnTouchListener y cambiar el fondo a verde cuando estaba seleccionado, PERO tengo botones dentro de las filas que podrían no funcionar debido a la implementación de OnTouchListener. ¿Es esto cierto?

Código:

public class MyAdapter extends BaseAdapter { 

    public View getView(int position, View convertView, ViewGroup parent) { 
     // position is the element's id to use 
     // convertView is either null -> create a new view for this element! 
     //    or not null -> re-use this given view for element! 
     // parent is the listview all the elements are in  

     if (convertView == null) { 
      convertView = mInflater.inflate(R.layout.your_layout, null); 

      // here you must do whatever is needed to populate the elements of your 
      // list element layout 
      ... 
     } else { 
      // re-use the given convert view 

      // here you must set all the elements to the required values 
     } 

     // your drawable here for this element 
     convertView.setBackground(...); 

     // maybe here's more to do with the view 
     return convertView; 
    } 
} 

Respuesta

2

Utilice un StateListDrawable con un tema definido para STATE_SELECTED.

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_selected="true" android:drawable="@drawable/selected" /> 
    ...Other States... 
    <item android:drawable="@drawable/normal" /> 
</selector> 

De esta manera, cuando se selecciona el elemento de la lista, usará ese gráfico "seleccionado" automáticamente.