longuid
longuid

Reputation: 116

How to refuse period in android EditText

sorry my english, I want to refuse keyup when user type . (KEYCODE_PERIOD) in EditText.

Here is my code;

<EditText 
     android:id="@+id/input"
     android:digits=".0123456789" 
     android:inputType="number" 
/>

and

input.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        return true;
    }
});

anything can not be pressed but the period. why?

Upvotes: 0

Views: 166

Answers (2)

scottt
scottt

Reputation: 8371

Assuming you're using a soft keyboard on a newer Android version, then the following blurb from the KeyEvent reference likely explains the reason you're not getting your expected key events.

"As soft input methods can use multiple and inventive ways of inputting text, there is no guarantee that any key press on a soft keyboard will generate a key event: this is left to the IME's discretion, and in fact sending such events is discouraged. You should never rely on receiving KeyEvents for any key on a soft input method. In particular, the default software keyboard will never send any key event to any application targetting Jelly Bean or later, and will only send events for some presses of the delete and return keys to applications targetting Ice Cream Sandwich or earlier. Be aware that other software input methods may never send key events regardless of the version. Consider using editor actions like IME_ACTION_DONE if you need specific interaction with the software keyboard, as it gives more visibility to the user as to how your application will react to key presses."

Upvotes: 0

Pankaj Arora
Pankaj Arora

Reputation: 10274

You should implement TextWatcher to detect user input and then compare the text on afterTextChanged() listener. Like below:

input.addTextChangedListener(new TextWatcher() {

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

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (input.getText().toString().equalsIgnoreCase("period")) {
            // do something
        } else {
            // do something else
        }
    }
});

Upvotes: 1

Related Questions