2015-06-21 30 views
0

如何驗證用戶輸入的是整數而不是無。用戶必須在editText中輸入一些內容,並且它必須是一個整數。我如何去驗證它。檢查用戶是否輸入了任何內容或字符串而不是整數

我有這樣的:

int age = Integer.parseInt(editAge.getText().toString()); 

if(editAge.getText().toString().equals("")){ 
     Toast messsage please try again 
}else they are good to go 

我不知道如何測試,如果編輯文本爲空或字符串輸入

+0

除了給,你也可以限制文本答案輸入的只是數字,在這裏看到:http://stackoverflow.com/questions/ 5200689/android-limiting-edittext-to-numbers –

回答

1

使用的Integer.parseInt()將輸入的字符串轉換成整數。如果成功,那麼它是一個整數。如果不是,它不是一個整數。

String text = editAge.getText().toString(); 
try { 
    int num = Integer.parseInt(text); 
    Log.d("",num+" is a number"); 
    // Good to go. 
} catch (NumberFormatException e) { 
    // Toast message. Please try again. 
} 
+1

謝謝,它工作 – user3330265

+0

不客氣。 –

0

而是驗證的,你可以使用輸入型像下面。這樣,用戶可以輸入數字只有

<EditText 
 
    android:layout_width="match_parent" 
 
    android:layout_height="wrap_content" 
 
    android:inputType="numberDecimal" 
 
    android:numeric="integer"/>

相關問題