从SD卡和GridView布局中删除照片

时间:2013-09-17 18:54:29

标签: android image photo android-sdcard android-file

我在下面有这个代码,我希望这样当我在GridView中长按我的照片时,我会选择删除。一切都很完美。但是当我点击删除时,它实际上并没有从我的GridView或SD卡目录中删除照片。

       switch (item.getItemId()) {
            case R.id.deletePhoto:
                new AlertDialog.Builder(getActivity()).setTitle("Delete Photo")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        photoGrid.setSelection(i);
                        final File dir = new File(GridViewDemo_ImagePath);
                        dir.mkdirs();
                        File[] files = dir.listFiles(new FilenameFilter() {

                            @Override
                            public boolean accept(File arg0, String arg1) {
                                return arg1.contains(".png");
                            }

                        });

                        File file = files[i].getAbsoluteFile();
                        file.delete();
                        Toast.makeText((MainActivity)getActivity(), "Photo deleted.", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNeutralButton("Cancel", null)
                .create()
                .show();
                break;

有没有人有任何想法如何做到这一点或我在我的代码中做错了什么?任何帮助或示例将不胜感激。提前谢谢!

2 个答案:

答案 0 :(得分:0)

你永远不会打电话/它永远不会被称为file.delete();

将此内置于对话框中

                    File file = files[i].getAbsoluteFile();
                    file.delete();
                    Toast.makeText((MainActivity)getActivity(), "Photo deleted.", Toast.LENGTH_SHORT).show();

            case R.id.deletePhoto:
            new AlertDialog.Builder(getActivity()).setTitle("Delete Photo")
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    photoGrid.setSelection(i);
                    final File dir = new File(GridViewDemo_ImagePath);
                    dir.mkdirs();
                    File[] files = dir.listFiles(new FilenameFilter() {

                    File file = files[i].getAbsoluteFile();
                    file.delete();
                    Toast.makeText((MainActivity)getActivity(), "Photo deleted.", Toast.LENGTH_SHORT).show();



                    });
               .setNeutralButton("Cancel", null)
            .create()
            .show();
            break;

答案 1 :(得分:0)

你必须把

                    File file = files[i].getAbsoluteFile();

                    file.delete();

内部

  public void onClick(DialogInterface dialogInterface, int i) {}

这样当您在对话框删除照片上按下确定按钮时,它将删除照片并调用方法删除;