Edittext 转换为字符串。

5

在Android上,我试图将Edittext转换为字符串。 toString()方法不起作用,当我打印输出时,playerName为空。是否有其他方法可以将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();
5个回答

8

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
    }
  };

edit to clarify:

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

我正在尝试将值保存到一个变量中,那么如果我在alert.show()之前声明另一个变量来保存它,这样行吗? - daveeloo
一般的问题是,alert.show()没有暂停调用void或函数的执行。在show()下面的代码将立即执行,而不等待OK。如果您想使用变量,可以将值存储到公共变量中,但只能在其他voids/function中使用它,而不能在对话框调用一个中使用(如vb或c#)。如果您想立即使用它,则必须在对话框的onclick方法中调用using函数,有时这必须在可运行的情况下进行。 - 2red13

5

editText.getText().toString() 可以获取一个字符串


它应该打印出playerName,但实际上却打印出了null。 - daveeloo
请检查您的玩家名称文本字段是否已正确初始化并分配给它? - Zoombie

5

以下是获取 EditText 文本的方法:

et = (EditText)findViewById(R.id.resource_id_of_edittext);
String text = et.getText().toString();

2
String mystring=input.getText().toString();

0
如果playerName被声明为String,则您不需要进行任何转换。 getText方法会给您一个CharSequence,您可以将其用作String
问题在于您正在“从头开始”创建input变量,因此它不会引用任何现有的View。 您应该这样做:
EditText input = findViewById(R.id.player);

然后你可以:

playerName = input.getText();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接