2014-02-14 41 views
0

我有一個帶有EditText的警告框。
當我嘗試將它與用戶輸入進行比較時,它沒有經過「if」。在EditText上使用if語句

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    AlertDialog.Builder alert = new AlertDialog.Builder(this); 

    alert.setTitle("Number of players: "); 


    final EditText input = new EditText(this); 
    alert.setView(input); 

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int whichButton) { 

     } 
    }); 

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int whichButton) { 
      // Canceled. 
     } 
    }); 

    alert.show(); 

它不會從這裏開始工作:

String newString = input.getText().toString(); 

if(newString.equals("2")) 

    { 
     System.out.print("lol"); 

    } 

感謝您的幫助!

+0

什麼時候在第二個列表中執行代碼? –

+0

它也onCreate – user3311120

+0

在你想要執行的方法中包裝代碼確定警報按鈕點擊然後調用方法在onClick方法 –

回答

1

你必須把你的第二個上市的代碼在你的按鈕中的一個(我猜你要按下OK按鈕後,將被執行)的OnClickListener

... 
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int whichButton) { 
     String newString = input.getText().toString(); 
     if(newString.equals("2")) { 
      System.out.print("lol"); 
     } 
    } 
}); 
... 

你不能指望顯示對話框後立即獲取用戶輸入。用戶根本沒有時間輸入任何內容。

+0

非常感謝! :D – user3311120

+0

很高興我能幫到你。如果它對您有幫助,請點擊左邊的複選標記以接受此答案。 –

0

我確定if工作正常,你只是沒有看到它。在android應用程序中使用System.out.print();不可取,因爲沒有控制檯輸出到。改爲使用Logcat

More info on the topic