Android - Listview delete item and Refresh

后端 未结 9 1839
耶瑟儿~
耶瑟儿~ 2020-12-06 02:16

I am trying to implement ListView with Delete functionality to delete item from the listview. I am successful to delete but failed to refresh the listview after deletetion o

9条回答
  •  Happy的楠姐
    2020-12-06 03:05

    I have the solution:

    If you want to delete a row from a list view clicking on the DELETE button of each of that row do this. Here you have an example of a custom adapter class with a name and a delete button. Every time you press the button the row is deleted

    public class UserCustomAdapter extends ArrayAdapter{ 
    
    Context context;
    int layoutResourceId;
    ArrayList data = new ArrayList();
    
    public UserCustomAdapter(Context context, int layoutResourceId,ArrayList data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }
    
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row = convertView;
        UserHolder holder = null;
    
    
        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
    
            holder = new UserHolder();
            holder.textName = (TextView) row.findViewById(R.id.textView1);
            holder.btnDelete = (Button) row.findViewById(R.id.button2);
            row.setTag(holder);
        } else {
            holder = (UserHolder) row.getTag();
    
        }
    
        User user = data.get(position);
    
    
        holder.btnDelete.setTag(position);
        holder.textName.setText(user.getName());
    
    
    
        holder.btnDelete.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
    
                String pos = v.getTag().toString();
                int _posicion = Integer.parseInt(pos);
                data.remove(_posicion);
                notifyDataSetChanged();
    
            }
        });
    
        return row;
    
    
    }
    
    static class UserHolder {
        TextView textName;
        Button btnDelete;
    }
    }
    

提交回复
热议问题