Roman
Roman

Reputation: 5388

How to properly set InputType for EditText?

I want my EditText content type as numeric. I set InputType which is 2 according to the reference. But it's still possible to input any character.

final EditText input = new EditText(this);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);

What am I doing wrong here?

I can't use XML, but I have EditTextPreference with android:inputType="number" and it works properly.

EDIT:

Here is some more code:

case R.id.set_counter:
AlertDialog.Builder setCounterDialog = new AlertDialog.Builder(this);
setCounterDialog.setTitle("Set counter value");

final EditText input = new EditText(this);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
InputFilter[] filter = new InputFilter[1];
filter[0] = new InputFilter.LengthFilter(4);
input.setFilters(filter);

setCounterDialog.setView(input);
setCounterDialog.setPositiveButton("Ok", new OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        String inputText = input.getText().toString();
        counter = Integer.parseInt(inputText);
        counterLabel = (TextView) findViewById(R.id.counter);
        counterLabel.setText(inputText);
    }
});
setCounterDialog.setNegativeButton("Cancel", null);
setCounterDialog.show();
return true;

Upvotes: 4

Views: 8019

Answers (3)

Ron
Ron

Reputation: 24235

First call with null, then call with input type number:

input.setRawInputType(null);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);

Upvotes: 1

droid kid
droid kid

Reputation: 7609

Try this:

InputType.TYPE_CLASS_PHONE

Upvotes: 1

Nathan Schwermann
Nathan Schwermann

Reputation: 31503

use just input type instead

input.setInputType(InputType.TYPE_CLASS_NUMBER);

Upvotes: 10

Related Questions