ArrayIndexOutOfBoundsException con adaptador Android personalizado para múltiples vistas en ListView


Estoy intentando crear un Adaptador personalizado para mi ListView ya que cada elemento de la lista puede tener una vista diferente (un enlace, alternar o grupo de radio), pero cuando intento ejecutar la Actividad que usa la ListView recibo un error y la aplicación se detiene. La aplicación está dirigida a la plataforma Android 1.6.

El código:

public class MenuListAdapter extends BaseAdapter {
 private static final String LOG_KEY = MenuListAdapter.class.getSimpleName();

 protected List<MenuItem> list;
 protected Context ctx;
 protected LayoutInflater inflater;

 public MenuListAdapter(Context context, List<MenuItem> objects) {
  this.list = objects;
  this.ctx = context;
  this.inflater = (LayoutInflater)this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  Log.i(LOG_KEY, "Position: " + position + "; convertView = " + convertView + "; parent=" + parent);
  MenuItem item = list.get(position);
  Log.i(LOG_KEY, "Item=" + item );

        if (convertView == null)  {
            convertView = this.inflater.inflate(item.getLayout(), null);
        }

        return convertView;
 }

 @Override
 public boolean areAllItemsEnabled() {
  return false;
 }

 @Override
 public boolean isEnabled(int position) {
  return true;
 }

 @Override
 public int getCount() {
  return this.list.size();
 }

 @Override
 public MenuItem getItem(int position) {
  return this.list.get(position);
 }

 @Override
 public long getItemId(int position) {
  return position;
 }

 @Override
 public int getItemViewType(int position) {
  Log.i(LOG_KEY, "getItemViewType: " + this.list.get(position).getLayout());
  return this.list.get(position).getLayout();
 }

 @Override
 public int getViewTypeCount() {
  Log.i(LOG_KEY, "getViewTypeCount: " + this.list.size());
  return this.list.size();
 }

}

El error que recibo:

    java.lang.ArrayIndexOutOfBoundsException
  at android.widget.AbsListView$RecycleBin.addScrapView(AbsListView.java:3523)
  at android.widget.ListView.measureHeightOfChildren(ListView.java:1158)
  at android.widget.ListView.onMeasure(ListView.java:1060)
  at android.view.View.measure(View.java:7703)

Sé que la aplicación está regresando de getView y todo parece estar en orden.

Cualquier idea sobre lo que podría estar causando esto sería apreciado.

Gracias,

-Dan

Author: Anthony Forloney, 2010-04-08

4 answers

El tipo de vista de elemento del que está regresando

getItemViewType() es >= getViewTypeCount().

 503
Author: Romain Guy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-26 08:03:49

La respuesta aceptada es correcta. Esto es lo que estoy haciendo para evitar el problema:

public enum FoodRowType {
    ONLY_ELEM,
    FIRST_ELEM,
    MID_ELEM,
    LAST_ELEM
}

@Override
public int getViewTypeCount() {
    return FoodRowType.values().length;
}

@Override
public int getItemViewType(int position) {
    return rows.get(position).getViewType();  //returns one of the above types
}
 17
Author: mtbomb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-19 07:54:09

El problema se produce cuando el valor de getItemType es incorrecto. Este valor debe ser un entero y debe ser de 0 a getViewTypeCount () -1.

 0
Author: sunil jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-08 05:46:13

La razón, es más probable porque el método getItemViewType está devolviendo los valores incorrectos! Cada fila en listview es una vista única. Mientras scrooling getItemViewType alcance más que el recuento de la vista.

Qué hacer? Cómo evitar el problema?

Primero determine la vista(fila) en su listview que se muestra primero.Mientras se desplaza utilice la ecuación del modulador

    @Override
    public int getItemViewType(int position) {
        return choseType(position);//function to use modular equation
    }
    @Override
    public int getViewTypeCount() {
        return 10;
    }

En este ejemplo hay diez vistas(10 fila).

private  int choseType(int position){
    if(position%10==0)
        return 0;
    else if(position%10==1)
        return 1;
    else if(position%10==2)
        return 2;
    else if(position%10==3)
        return 3;
    else if(position%10==4)
        return 4;
    else if(position%10==5)
        return 5;
    else if(position%10==6)
        return 6;
    else if(position%10==7)
        return 7;
    else if(position%10==8)
        return 8;
    else
        return 9;


}

Importante

Algunos usuarios mencionaron en otra pregunta sobre stackoverflow ese método

Public int getViewTypeCount() y public int getItemViewType(int position) arreglan como Tooglebutton automáticamente habilitar la comprobación de estado true en scrooling.. eso es un gran error.Si usted no quiere automático enbale en scrool solo hacer

toogleButton.setChecked(false);

En el método getView override.

 -3
Author: Beyaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-17 06:02:20