EditText 对话框输入始终为空 (Android)

EditText dialog input always null (Android)

以下代码在按钮的 onClick 方法中运行并弹出对话框。我可以输入文本并按确定,但我的字符串文件名(如 Log.d 中所示)始终为空。我不明白为什么。

如何将对话框中输入的文本保存起来?

我的代码在 activity(无片段)中运行,字符串文件名和 EditText 输入都是 class 成员变量。

  // Get filename from user
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Enter filename");

    // EditText to get user input
    this.input = new EditText(this);
    dialog.setView(input);

    dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            filename = input.getText().toString();
        }
    });

    dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            // cancelled
        }
    });
    dialog.show();
    Log.d(LOG_TAG, "Filename is : " + filename);

我的代码基于 android prompt user's input using a dialog 但我的问题不同。

您在实际输入数据之前尝试记录字符串。 尝试将日志放在积极的 onClick 中,我想你会看到它确实保存了。

像这样:

// Get filename from user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enter filename");

// EditText to get user input
this.input = new EditText(this);
dialog.setView(input);

dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        filename = input.getText().toString();
        Log.d(LOG_TAG, "Filename is : " + filename);
    }
});

dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // cancelled
    }
});
dialog.show();