filtering custom adapter IndexOutOfBoundsException

前端 未结 4 1326
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 00:05

I\'m novice at android.

My custom Adapter cause exception when filtering.

here is my code. private class DeptAdapter extends ArrayAdapter implements Filter

4条回答
  •  抹茶落季
    2021-01-18 00:21

    Keep in mind that getView() will query the size of the items that the superclass has, which right now, is what you originally passed it when calling the superclass constructor,

    super(context, textViewResourceId, items);
    

    Therefore, the superclass doesn't know that you've changed the size when you have filtered. This means getCount() will return the original size of the array, which is understandably larger than your filtered array.

    This means You should override the getCount() method so you're sure that you're returning the actual valid size:

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

    You should also override the other methods related to the List operations (such as getting) if you are going to be using them. Eg:

    @Override
    public Dept getItem (int pos){
         return items.get(pos);
    }
    

提交回复
热议问题