从输入对话框中的编辑文本中获取文本

时间:2013-07-01 19:44:16

标签: android text dialog alert edit

我有一个这样的警告对话框:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            context);
    EditText input = new EditText(this);
    input.setText(sp.getString("NAME_0",""),TextView.BufferType.EDITABLE);
    alertDialogBuilder.setView(input);
    String name = input.getText().toString();
    alertDialogBuilder.setCancelable(false);
    alertDialogBuilder.setTitle("Enter your name"); //Set the title of the box
    //alertDialogBuilder.setMessage(""); //Set the message for the box
    alertDialogBuilder.setPositiveButton("Start", new DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog, int id){
            dialog.cancel(); //when they click dismiss we will dismiss the box
        }
    });
    AlertDialog alertDialog =alertDialogBuilder.create(); //create the box
    alertDialog.show(); //actually show the box

问题是“名字”似乎总是空的。是否有不同的方法从警报对话框中的编辑文本中获取文本?

2 个答案:

答案 0 :(得分:2)

方法工作正常你只是过早地分配变量,你需要这样做,例如当用户点击onClick()中的按钮时

答案 1 :(得分:1)

尝试以下方法:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
        context);
EditText input = new EditText(this);
input.setText(sp.getString("NAME_0",""),TextView.BufferType.EDITABLE);
alertDialogBuilder.setView(input);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setTitle("Enter your name"); //Set the title of the box
//alertDialogBuilder.setMessage(""); //Set the message for the box
alertDialogBuilder.setPositiveButton("Start", new DialogInterface.OnClickListener(){
    public void onClick(DialogInterface dialog, int id){
        String name = input.getText().toString();
        dialog.cancel(); //when they click dismiss we will dismiss the box
    }
});
AlertDialog alertDialog =alertDialogBuilder.create(); //create the box
alertDialog.show(); //actually show the box

您在创建对话框时尝试使用EdtiText的值,该对话框为空。