How to toast when letter is inputed in EditText

623 views Asked by At

I am a beginner starting to design a simple app to keep track of golf scores. I spent some time trying to figure out how to provide the user with a notification that they are unable to enter a letter under the score text box. I have tried using an array that contains the entire alphabet but have not been able to get it to work. I am currently now experimenting with InputFilter but I am not having any success; the app simply crashes when a letter has been entered.

    EditText input1 = (EditText)findViewById(R.id.scorePrompt);
    TextView output1 = (TextView)findViewById(R.id.textTotal);
    String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING

    InputFilter filter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            for (int i = start; i < end; i++) {
                if (Character.isLetter(source.charAt(i))) { // Accept only letter & digits ; otherwise just return
                    Toast.makeText(getApplicationContext(),"NO LETTERS",Toast.LENGTH_SHORT).show();
                    return "";
                }
            }
            return null;
        }
    };

I suspect that it is because I am not directly connecting the Inputfilter to my blankCheck, but I am unsure. Any help is appreciated!

2

There are 2 answers

2
themichaelscott On

Often the answer you're looking for is a result of a problem that originates elsewhere.

If you'd like your users to input numbers rather than text, the best solution would be to specify an input type of "number" on the EditText field they are typing in. This will limit the keyboard input to only allow numbers.

<EditText
    android:inputType="number"
    .... other attributes
</EditText>
0
Ashray P. Shetty On

U can make use of Regex for this, please see the below code :

// Define a pattern you want to use as below. // I'm only supporting the below :

Pattern keyPattern = Pattern.compile("[0-9a-zA-Z,._]+");

yourEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable s) {
    if (!keyPattern .matcher(yourEditText.getText()).matches()) {
        Toast.makeText(getApplicationContext(),"Your Message",Toast.LENGTH_SHORT).show();
                    return "";
 }
});

Hope this helps!!!