5

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?

Cristian
  • 198,401
  • 62
  • 356
  • 264
User616263
  • 467
  • 2
  • 9
  • 23

2 Answers2

13

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:

enter image description here

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:

enter image description here

Cristian
  • 198,401
  • 62
  • 356
  • 264
0

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();
    }
}
Robby Pond
  • 73,164
  • 16
  • 126
  • 119