2011-05-10 115 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();