Android:添加验证以确保用户只能输入数字

时间:2014-05-08 18:25:54

标签: android validation android-edittext

在我的应用程序中,我正在从用户那里获取数学游戏的答案。输入答案后,将显示下一个问题等。 目前,如果问题得到解答并且错误地输入了字母或空白答案,则应用程序崩溃。 我希望应用程序只是在用户无效的情况下不接受用户的答案,并且在给出有效答案(数字)之前继续显示问题。

当前代码:

// sets text view equal to what is entered in editText
        final String entry = answer.getText().toString();
        // convert from string value to int
        int a = Integer.parseInt(entry); //

        // setting the user answer equal to the correct part of results array
        results[questionNumber - 1] = a;

        // If user answer is equal to correct answer then increase score
        if (a == correctAnswer[questionNumber - 1]) {
            score++;
            correctNoise.start();
            imageRandom.setImageResource(R.drawable.thumbsup);
        }else{

            incorrectNoise.start();
            imageRandom.setImageResource(R.drawable.thumbsdown);

        }

5 个答案:

答案 0 :(得分:4)

只需将android:inputType="number"添加到EditText xml视图即可。如果要在代码中检查它,将检查String是否为数字:

public static boolean isNumeric(String str)  
{  
  try  
  {  
    double d = Double.parseDouble(str);  
  }  
  catch(NumberFormatException nfe)  
  {  
    return false;  
  }  
  return true;  
}

来源:How to check if a String is numeric in Java

答案 1 :(得分:1)

您应该强制执行InputType的{​​{1}}。这将使数字键盘显示。例如,要在 XML 中执行此操作:

EditText

或来自代码:

android:inputType="numberSigned"

最后,确保输入不为空:

answer.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_SIGNED);

答案 2 :(得分:1)

Integer.parseInt()可以抛出NumberFormatException。

您可以尝试像这样包装它,然后通过拒绝用户的答案来处理异常:

try {
    int a = Integer.parseInt(entry);
} catch(NumberFormatException ex) {
    // do something to handle the error
}

您还可以要求Android键盘使用以下方式显示数字:

android:inputType="number"
上的

答案 3 :(得分:-1)

// sets text view equal to what is entered in editText

    if(answer.getText()!=null) {
    final String entry = answer.getText().toString();
    // convert from string value to int
    int a = Integer.parseInt(entry); //

    // setting the user answer equal to the correct part of results array
    results[questionNumber - 1] = a;

    // If user answer is equal to correct answer then increase score
    if (a == correctAnswer[questionNumber - 1]) {
        score++;
        correctNoise.start();
        imageRandom.setImageResource(R.drawable.thumbsup);
    }else{

        incorrectNoise.start();
        imageRandom.setImageResource(R.drawable.thumbsdown);

    }
}

答案 4 :(得分:-1)

要确保用户首先输入数字,您可以使用

answer.setinputtype(inputtype.number);

和第二个写一个函数来检查值是数字

public static boolean tryParseInt(String value )  
    {  
         try  
         {  
             Integer.parseInt(value);  
             return true;  
          } catch(NumberFormatException nfe)  
          {  
              return false;  
          }  
    }