在Android上,我试图将Edittext转换为字符串。 toString()方法不起作用,当我将其打印出来时,playerName为null。还有其他方法可以将edittext转换为字符串吗?

AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setMessage("Your Name");
        final EditText input = new EditText(this);
        alert.setView(input);
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                playerName = input.getText().toString();
            }
        });
        alert.show();

最佳答案

alertdialog看起来不错,但错误可能出在代码的其余部分。您必须记住,您不能仅在对话框的show()之前使用var playerName,如果要打印名称,则应使用可运行的方式(在此处调用)进行操作:

      static Handler handler = new Handler();

      [.......]

      public void onClick(DialogInterface dialog, int whichButton) {
            playerName = input.getText().toString();
            handler.post(set_playername);

      }

      [.......]

     static Runnable set_playername = new Runnable(){
            @Override
            public void run() {
        //printout your variable playerName wherever you want
    }
  };

编辑以澄清:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setMessage("Your Name");
    final EditText input = new EditText(this);
    alert.setView(input);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            playerName = input.getText().toString();
            //call a unction/void which is using the public var playerName
        }
    });
    alert.show();
    // the variable playerName is NULL at this point

10-06 03:35