2011-05-17 93 views
0

基本上我有一個文本框,看起來像這樣一個EditText框:比較字符串數組內容與內容的EditText

用戶名[]

然後在底部有一個名爲「提交」按鈕。

簡而言之,我必須輸入一個用戶名,將其與我在strings.xml文件中的字符串數組進行比較,如果它不等於數組中的任何字符串,那麼我很好走。

的字符串數組是這樣的:

< string-array name="usernames"> <項目>布萊恩 < item>John</item> <項目>馬特 < item>Mike</item> < /字符串數組>

我很困惑,我該怎麼做一個簡單的,如果聲明,在僞代碼看起來像:

if(username_entered_in_editText == usernameArray [contents]) {submit_check = true; }

任何意見將不勝感激!

回答

0

嘗試這樣的事情。獲取String []的實例,使用getText()。toString()從EditText獲取文本,然後比較列表中的每個名稱。當然,這不是最優化的。如果你的String數組是排序的,你可以實現一個二進制搜索來使其更快,但是這裏的一般理論是可行的。

String[] usernames = getStringArray(R.array.usernames); 
EditText editText = (EditText)findViewById(R.id.edittext); 
String candidate = editText.getText().toString(); 
boolean submit_check = usernameTaken(candidate, usernames); 

public boolean usernameTaken(String candidate, String[] usernames) { 
    for(String username : usernames) { 
     if(candidate.equals(username)) { 
      return true; 
     } 
    } 
    return false; 
}