如何从AlertDialog获取结果?

fin*_*oop 23 android android-edittext android-alertdialog

我正在使用AlertDialog.Builder来显示一个提示用户输入密码的对话框,然后我想在偏好中保存该密码,但是我无法弄清楚如何从警告对话框的输入方法中获取结果.

这基本上是我希望能够做到的:

    String result;
    AlertDialog.Builder b = new AlertDialog.Builder(this);
    b.setTitle("Please enter a password");
    final EditText input = new EditText(this);
    b.setView(input);
    b.setPositiveButton("OK", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int whichButton)
        {
           //I get a compile error here, it wants result to be final.
           result = input.getText().toString();
        }
    });
    b.setNegativeButton("CANCEL", null);
    b.create().show();
Run Code Online (Sandbox Code Playgroud)

但是,我愿意做一些事情,比如showDialog(int);然后使用onCreateDialog(int)方法并以某种方式设置结果并以其他方法接收它,但我不知道如何去做最后一部分.

Fem*_*emi 24

public class MyActivity extends Activity {
    private String result;

    void showDialog() {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle("Please enter a password");
        final EditText input = new EditText(this);
        b.setView(input);
        b.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int whichButton) {
                result = input.getText().toString();
            }
        });
        b.setNegativeButton("CANCEL", null);
        b.show();
    }
}
Run Code Online (Sandbox Code Playgroud)