Edittext to String

dav*_*loo 4 android android-edittext

在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();
Run Code Online (Sandbox Code Playgroud)

2re*_*d13 7

alertdialog看起来很好,但可能错误位于代码的其余部分.你必须要记住,你不能在对话框的show()之前使用var playerName,如果你想要打印出你应该用你在这里调用的runnable这样做的名字:

      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
    }
  };
Run Code Online (Sandbox Code Playgroud)

编辑澄清:

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
Run Code Online (Sandbox Code Playgroud)


Jan*_*nen 5

以下是从 EditText 中获取文本的方法

et = (EditText)findViewById(R.id.resource_id_of_edittext);
String text = et.getText().toString();
Run Code Online (Sandbox Code Playgroud)


Zoo*_*bie 5

editText.getText().toString() 给你一个字符串