从AlertDialog返回字符串

时间:2012-09-04 20:12:23

标签: android android-alertdialog

我正在研究android项目,我正在尝试显示一个包含CharSequence数组的AlertDialog,当单击它时,它应该返回该字符串。

以下是我正在使用的代码

String fileName = "";
        //Collect the files from the backup location
        String filePath = Environment.getExternalStorageDirectory().getPath() + "/BoardiesPasswordManager";
        File f = new File(filePath);

        File[] files = f.listFiles();
        final CharSequence[] fileNames = new CharSequence[files.length];
        if (files.length > 0)
        {
            for (int i = 0; i < files.length; i++)
            {
                fileNames[i] = files[i].getName();
            }
        }

        String selectedFile = "";
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("Choose Backup File");
        builder.setItems(fileNames, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int item) {
                fileName = fileNames[item].toString();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();

        return fileName;

正如您所看到的,我正在尝试将fileName设置为Array中的选定项,但Eclipse一直说String fileName需要final类型,但显然我可以' t将其设置为所选字符串的值。如何设置变量以便我可以返回字符串。

感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:1)

这里的问题是对何时执行'return fileName'的误解。显然,只有在用户做出选择后执行此代码才有效。但是,它实际上会在之前执行。实际上,它会在您调用alert.show()后立即执行。

最好从函数范围中删除fileName,并在click事件中添加函数调用,如:

public void onClick(DialogInterface dialog, int item){
    String fileName = fileNames[item].toString();
    doSomethingWithTheFile(fileName);
}

此外,您的原始功能将不再返回任何内容,它只会设置您的对话框。