如何在Android java上打开选择目录对话框?

时间:2014-03-21 08:40:34

标签: android

我的应用程序从互联网上下载文件,我需要用户选择保存位置。如何在Android Java上创建一个选择目录?请提供示例代码

2 个答案:

答案 0 :(得分:0)

检查出来:

小型开源Android库项目,简化了这一过程,同时还提供了内置的文件浏览器(如果用户没有一个存在)。它使用起来非常简单,只需要几行代码。

您可以在GitHub找到它:https://github.com/iPaulPro/aFileChooser

更多详情:

Android file chooser

答案 1 :(得分:0)

您只需在以下活动中覆盖onCreateDialog

//In an Activity
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";    
private static final int DIALOG_LOAD_FILE = 1000;

private void loadFileList() {
    try {
        mPath.mkdirs();
    }
    catch(SecurityException e) {
        Log.e(TAG, "unable to write on the sd card " + e.toString());
    }
    if(mPath.exists()) {
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String filename) {
                File sel = new File(dir, filename);
                return filename.contains(FTYPE) || sel.isDirectory();
            }

        };
        mFileList = mPath.list(filter);
    }
    else {
        mFileList= new String[0];
    }
}

protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    AlertDialog.Builder builder = new Builder(this);

    switch(id) {
        case DIALOG_LOAD_FILE:
            builder.setTitle("Choose your file");
            if(mFileList == null) {
                Log.e(TAG, "Showing file picker before loading the file list");
                dialog = builder.create();
                return dialog;
            }
            builder.setItems(mFileList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    mChosenFile = mFileList[which];
                    //you can do stuff with the file here too
                }
            });
            break;
    }
    dialog = builder.show();
    return dialog;
}