使用imageview删除listview中的行

时间:2014-08-25 06:44:51

标签: android listview imageview

如何在listview上实现删除行。我希望能够在用户点击' x'时删除该行。 (ImageView的)。 代码在这里:

listView.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // When clicked, show a toast with the TextView text
                    String str = listView.getItemAtPosition(position).toString();
                    Toast.makeText(getApplicationContext(), str , Toast.LENGTH_SHORT).show();

                    ImageView ivDel = (ImageView) findViewById(R.id.ivClose);
                    ivDel.setOnClickListener(
                                    new OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                    Toast.makeText(getApplicationContext(), "delete" , Toast.LENGTH_SHORT).show();
                                            }
                                    });
                }

            });

&#39; x&#39;按钮仅在第一行上工作,其余部分不起作用。

enter image description here

2 个答案:

答案 0 :(得分:0)

试试这个

    int position = listview1.getPositionForView((View) v.getParent());
    yourList.remove(position);
    yourAdapter.notifyDataSetChanged();

答案 1 :(得分:0)

1

 public interface DeleteListIteamListner {
    void itemDeleteListner(int position);
}

2

yourActivity implements DeleteListIteamListner 
 youAdapter adapter = new youAdapter (yourActivity);
listView.setAdapter(adapter);
你在adadter中

3,

DeleteListIteamListner  listner;
   public youAdapter (yourActivity listner){
       this.listner = listner;
   }

然后当你点击删除imageView:

ImageView ivDel = (ImageView) findViewById(R.id.ivClose);
                    ivDel.setOnClickListener(
                                    new OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                              listner.itemDeleteListner(position);  
                                            }
                                    });

和youActivity

@Override
    public void itemDeleteListner(int position){
yourList.remove(position);
yourAdapter.notifyDataSetChanged();
 Toast.makeText(getApplicationContext(), "delete position is "+ position , Toast.LENGTH_SHORT).show();
}