使用对话android从listview中删除项目


lstv = (ListView) findViewById(R.id.lista);
lstv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int posicion, long id) {
                removeItemFromList(posicion);
            }
        });
    }

    protected void removeItemFromList(final int position) {
        final int deletePosition = position;
        AlertDialog.Builder alert = new AlertDialog.Builder(
                Apple.this);
        alert.setTitle("Delete");
        alert.setMessage("¿Do you want delete?");
        alert.setPositiveButton("Si", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
Help here please...!!
            }
        });

        alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        alert.show();

您还需要将项的数组列表传递给函数,删除后需要运行函数notifyDataSetChanged();,此函数将重新构建列表视图。所以:

AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
    alertDialog.setTitle("title...");
    alertDialog.setMessage("Are you sure you want delete this?");
    alertDialog.setIcon(R.drawable.delete);
    alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
                  mArrayList.remove(position);
                  mArrayAdapter.notifyDataSetChanged();

        Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
        }
    });

    alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
        dialog.cancel();
        }
    });
    // Showing Alert Message
    alertDialog.show();

参考此

修改arrayList

然后

arrayList.remove([INDEX]);
arrayAdapter.notifyDataSetChanged();

现在,如果需要,再次将adapter设置为ListView

在Alert.Dialog方法中添加此代码

alert.setPositiveButton("Si", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        itemList.remove(favTransPosition);
                        adapter.notifyDataSetChanged();                         
                        adapter = new ArrayAdapter<String>(, , , itemList); // Fill remaining params as you have created earlier
                        lstv.setAdapter(adapter);                       
                    }
                });

最新更新