Balfas
Balfas

Reputation: 53

EditText setInputType(InputType.TYPE_CLASS_NUMBER); don't work

I am try using create one editText that only receive numeric (only appears numeric keyboard). On nexus 7 that don't happen :X

this is my code:

    EditText edit = new EditText(context);
    edit.setText(value);
    edit.setTextSize(16);
    edit.setTextColor(getResources().getColor(R.color.blue));
    edit.setInputType(InputType.TYPE_CLASS_NUMBER
            | InputType.TYPE_NUMBER_FLAG_DECIMAL);
    edit.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            elem.setValue(s.toString());
        }

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

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

Can you help me?

EDIT:

i am add this EditText to a LinearLayout like this:

    myLinearLayout.addView(edit);

Upvotes: 2

Views: 6187

Answers (3)

Rajaji subramanian
Rajaji subramanian

Reputation: 288

try this it will help you

change, instead of this line

edit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

change like below

edit.setRawInputType(InputType.TYPE_CLASS_NUMBER |InputType.TYPE_NUMBER_FLAG_DECIMAL);

Upvotes: 8

Gabe Sechan
Gabe Sechan

Reputation: 93559

That's not what numeric does. Numeric is a hint to the keyboard that it should show a numberpad. It does not force the keyboard to do that, and it does not prevent other keys (like +, -, #, *, etc) from being shown or entered. If you want to prevent certain characters from being entered, you have to do that app side. If you want to do that, you need to set an InputFilter on the edit field.

Here's some code for that:

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.isDigit(source.charAt(i))) { 
                                return ""; 
                        } 
                } 
                return null; 
        } 
}; 
edit.setFilters(new InputFilter[]{filter}); 

Upvotes: 1

Tr4X
Tr4X

Reputation: 299

Try to use TextView.setRawInputType(), the java equivalent of android:inputType

Upvotes: 1

Related Questions