I have an XML layout file that contains an EditText
and a Button
. I would like to display the following validation message to provide feedback to the user:
You must enter 4 numbers
What's the best way to go about accomplishing this?
I have an XML layout file that contains an EditText
and a Button
. I would like to display the following validation message to provide feedback to the user:
You must enter 4 numbers
What's the best way to go about accomplishing this?
From my experience, this is the best way:
EditText yourEditText;
// when you detect an error:
yourEditText.setError("Input must be 4 digits and numeric");
The result is:
Also, if the input must be numeric, use android:inputType="numberSigned"
in the EditText
definition. That way the device won't allow the user to put non-numeric values; even better, it will show a special keyboard to do so:
On the EditText definition in the xml use android:numeric to bring up the numeric IME and use android:maxLength = "4" to limit the input to 4 digits. Use android:onClick on the button to trigger a click handler.
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();
}
}