2011-05-10 116 views
2

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

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(); 

回答

6

alertdialog看起来不错,但也许错误位于代码的其余部分。你必须记住,你不能使用var playerName只是对话框的show(),如果你想打印出你应该这样做的名字,你可以在这里调用一个可运行的命令:

 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 
+0

我试图将值保存到一个变量,所以如果我在alert.show()之前声明另一个变量来保存它,那会起作用吗? – daveeloo 2011-05-10 08:28:29

+0

一般问题是,alert.show()不会暂停调用void或function的执行。 show()的代码将立即执行,并不等待OK。如果你想使用这个变量,你可以将这个值存储到一个公共变量中,但是你只能在其他void/function中使用它,而不是在调用它的对话框中使用它(如在vb或c#中)。如果你想立即使用它,你需要在对话框的onclick方法中调用using函数,并且每次都必须处于可运行状态 – 2red13 2011-05-10 09:18:21

0

如果playerName被声明为String,你不应该需要转换它或任何东西。 getText方法为您提供了一个CharSequence,您可以使用它作为String

问题是你正在创建你的input变量“从零开始”,所以它不会引用任何现有的View。你应该这样做:

然后你可以:

playerName = input.getText(); 
3

这里是你如何获取文本出来的EditText

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

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

+0

它应该,但playerName打印空。 – daveeloo 2011-05-10 08:00:15

+0

检查您的playername文本字段是否已正确初始化并分配给它? – Zoombie 2011-05-10 09:03:40

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