显示验证消息

时间:2011-02-22 19:29:05

标签: android validation android-edittext

我有一个包含EditTextButton的XML布局文件。我想显示以下验证消息以向用户提供反馈:

  

您必须输入4个数字

实现这个目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:13)

根据我的经验,这是最好的方式:

EditText yourEditText;

// when you detect an error:
yourEditText.setError("Input must be 4 digits and numeric");

结果是:

enter image description here

此外,如果输入必须为数字,请在android:inputType="numberSigned"定义中使用EditText。这样设备将不允许用户输入非数字值;更好的是,它会显示一个特殊的键盘:

enter image description here

答案 1 :(得分:0)

在xml中的EditText定义中,使用android:numeric调出数字IME并使用android:maxLength =“4”将输入限制为4位数。使用按钮上的android:onClick来触发点击处理程序。

public void onClick(View v) {
    if(mEditText.length() != 4) { // check if 4 digits
        Toast.makeText(this, "Input must be 4 digits and numeric", Toast.LENGTH_SHORT).show();
    }
}