2011-07-02 11 views
0

我有一個只有150個文件的搜索應用程序。因此,如果有人搜索151,則會說「無法找到文件151」EditText等於

我的代碼:

EditText edit = (EditText) findViewById(R.id.editText1); 

if (edit.getText().toString().equals("151")) { 
    edit.setError("Invalid File Name"); 
} else { 
    // Do nothing; 
} 

但我有2個問題:

  1. 如何設置.equals("151")喜歡的東西:.equals("151" >)(151及以上)?
  2. 什麼是「無所事事」的代碼?

回答

1
  1. 您創建的字符串一個int。像這樣:

    int aInt = Integer.parseInt(edit.getText().toString()); 
    
    if(aInt > 150) 
    dostuff(); 
    
  2. 什麼都不做,只需添加「;」。

    if(foo) 
    dostuff(); 
    else 
    ; 
    
+0

謝謝,這是工作,真的很感謝你。 – Gromdroid

+0

不客氣。但正如Trev16v所提到的,你必須準備好捕捉數字形象。這意味着如果用戶輸入「foo」,並嘗試將該字符串解析爲int,則會遇到麻煩。 – Emiam

1

您需要將EditText的值解析爲Integer,以便您可以使用運算符進行比較。像這樣:

if (Integer.valueOf(edit.getText().toString()) > 150) {do stuff;}) 

你可能想先分析它(一個try catch塊),然後做的if/else根據該值是否在範圍之內。爲了向用戶顯示快速驗證消息,您可能需要使用Toast通知。

+0

不,這不工作;它表示:運算符>未定義爲參數類型(s)字符串,int – Gromdroid

+0

哎呦,錯過了括號,修正了。 – dmon

0

你可以把它這樣

int num = Integer.parse(edit.getText().toString()); 
if(num >= 151) { 

} else { 
} 
0

你需要分析它作爲一個整數,你還需要處理,其中字符串不能被解析爲整數的情況。如果值來自用戶輸入,您必須準備好趕上NumberFormatException!

try{  
    int i = Integer.parseInt(edit.getText().toString()); 

    if(i>150){ 
     // Do stuff if i > 150 
    } 
    else{ 
     // Stuff if i < 151 
    } 

}catch(NumberFormatException e){ 
    // Deal with the fact that the file name is not a valid integer number (e.g. "ABC") 
}