【问题标题】:Comparing string array content with EditText content将字符串数组内容与 EditText 内容进行比较
【发布时间】:2011-05-17 23:44:47
【问题描述】:

基本上我有一个文本框和一个如下所示的编辑文本框:

用户名 [ ]

然后在底部有一个叫做“提交”的按钮。

很简单,我必须输入一个用户名,将其与我的 strings.xml 文件中的字符串数组进行比较,如果它不等于数组中的任何字符串,那么我很高兴.

字符串数组如下所示:

string-array name="usernames"> <item>布莱恩 item>John</item> <item>马特 item>Mike</item> </string-array>

我很困惑如何在伪代码中执行一个简单的 if 语句,如下所示:

if (username_entered_in_editText == usernameArray[contents]) { 提交检查 = 真; }

任何建议将不胜感激!

【问题讨论】:

    标签: android xml string


    【解决方案1】:

    试试这样的。获取 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-11
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多