Deleting items from a ListView using a custom BaseAdapter

只谈情不闲聊 提交于 2019-12-03 03:08:24

You have to set the position each time. Your implementation only sets the position on the creation of the view. However when the view is recycled (when convertView is not null), the position will not be set to the correct value.

    public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.language_link_row, null);
        holder = new ViewHolder();
        holder.lang = (TextView)convertView.findViewById(R.id.language_link_text);

        final ImageView deleteButton = (ImageView) 
                convertView.findViewById(R.id.language_link_cross_delete);
        deleteButton.setOnClickListener(this);

        convertView.setTag(holder);
        deleteButton.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.lang.setText(mLanguages.get(position));
    holder.position = position;
    return convertView;
}

you need to implement OnItemClickListener interface, and delete the item in the onItemClick method, one parameter of the method is the position.

My final solution was to use the accepted answer by Greg and the following:

  • Store the holders in a HashMap, with the item positions as the keys (this is initialised as empty in the constructor)

    private HashMap mHolders;

  • Use this as the onClickListener method:

public void onClick(View v) {
    ViewHolder deleteHolder = (ViewHolder) v.getTag();
    int pos = deleteHolder.position;
    mHolders.remove(pos);

    ViewHolder currentHolder;

    // Shift 'position' of remaining languages 
    // down since 'pos' was deleted
    for(int i=pos+1; i<getCount(); i++){
        currentHolder = mHolders.get(i);
        currentHolder.position = i-1;
    }
    mLanguages.remove(pos);
    notifyDataSetChanged();
}

[Please excuse the weird formatting. The code embedding isn't working properly]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!