如何在用户单击该行内的按钮时从自定义ListView中删除行

时间:2014-03-09 10:27:05

标签: android android-listview

我已经创建了一个自定义列表视图并用数据填充它,但我发现很难删除一行放在同一行内的按钮。下面是适配器的代码。如何删除此行。任何想法??

public Pursue_results_listview_adapter(Context c, String[] ClientName,
        String[] clientId) {
    super(c, R.layout.pursuing_list_row, R.id.client, ClientName);
    this.context = c;
    this.clientIdArray = clientId;
    this.ClientNameArray = ClientName;
}

class viewHolder {
    TextView client;
    ImageView deleteclient;

    public viewHolder(View v) {

        deleteclient = (ImageView) v.findViewById(R.id.deleteclient);
        client = (TextView) v.findViewById(R.id.client);

    }
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View row = convertView;
    viewHolder holder = null;
    if (row == null) {

        LayoutInflater inflator = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflator.inflate(R.layout.pursuing_list_row, parent, false);
        holder = new viewHolder(row);
        row.setTag(holder);
    } else {
        holder = (viewHolder) row.getTag();
    }

    final String clientid = cleintIdArray[position];

    holder.client.setText(ClientNameArray[position]);

    holder.deleteclient.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //delete client

                           notifyDataSetChanged();
        }
    });

    return row;
}

3 个答案:

答案 0 :(得分:2)

试试这个

holder.deleteclient.setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        int index = Integer.parseInt(v.getTag().toString())
        data.remove(index); //where 'data' is your list
        notifyDataSetChanged();
    }
});

答案 1 :(得分:0)

尝试设置标记中的位置,如setTag(position),然后在onClick中移除位置,如

Integer i= (Integer) view.getTag();
list.remove(i.intValue()); 

答案 2 :(得分:0)

尝试这样的事情,还有什么理由你没有使用某种集合来保存你的数据?它会使它变得更加简单。

首先将clientIdArray和clientNameArray转换为Arraylists

Arraylist<String> clientIdArray;
Arraylist<String> clientNameArray;

然后改变这个

this.clientIdArray = clientId;
this.ClientNameArray = ClientName;

this.clientIdArray = new Arraylist<String>(Arrays.asList(clientId));
this.ClientNameArray = new Arraylist<String>(Arrays.asList(ClientName));

然后你的代码变成了这个

//Store the index that is being deleted in this views tag
holder.deleteclient.setTag(position)
holder.deleteclient.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) 
    {
        //get the index back
        int index = (Integer)v.getTag();

        //Removal code goes here, if you don't want to make your arrays into arraylists 
        //you will need to write your own removal code
        clientIdArray.remove(index);
        ClientNameArray.remove(index);

        notifyDataSetChanged();
    }
});