Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Simple ListView Element in android

Tags:

android

I am displaying Simple ListView. On long press event, Dialog is displayed to remove that item from ListView. Here is my code:

myList = (ListView) findViewById(R.id.listSendEmailFinal);

myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
        return onLongListItemClick(v,pos,id);
}
protected boolean onLongListItemClick(View v, final int pos, long id) {
        final String str=myList.getItemAtPosition(pos).toString();
        Log.i("ListView", "onLongListItemClick stirng=" + str);
        AlertDialog.Builder builder = new  
                AlertDialog.Builder(EmailReceiversActivity.this);
            builder.setMessage("Are you sure you want to exit?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {

                       }
                   })
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                       }
                   });
            AlertDialog alert = builder.create();
            alert.show();
            return true;
        }

    });

When I press 'Yes' Button, that item should be removed from listview.I've used ArrayAdapter. And 'listItems' is a string array

 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listItems);
 myList.setAdapter(adapter);

Please help me.

like image 465
Krishna Suthar Avatar asked Jul 01 '26 18:07

Krishna Suthar


2 Answers

in click event of yes button Just remove the item from "listItems" and call adapter.notifyDataSetChanged();

Thats it..!

like image 178
Shankar Agarwal Avatar answered Jul 04 '26 06:07

Shankar Agarwal


Just Try this inside the YES button click:

listItems.remove(pos);
adapter.notifyDataSetChanged();
like image 37
Paresh Mayani Avatar answered Jul 04 '26 07:07

Paresh Mayani