Peter
Peter

Reputation: 2500

Edittext Numeric by code

Hello guys.

I trying set EditText to input only numbers and point (" . ") that's all. Im already using inputType.. but there numeric keyboard with "+","-" and "#" and without point/period (".") example for what need it : 100.99 .. that's all. I found some code :

<EditText android:text="100.99"
android:id="@+id/EditText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numeric="integer|decimal" />

but it's in xml... i want create it by code. Also i mean this string :

 android:numeric="integer|decimal"

Please if any one know how to set this settings by code.. reply me

Regards, Peter.

Upvotes: 0

Views: 1357

Answers (3)

user3178073
user3178073

Reputation: 1

actually this works:

editText.setInputType((InputType.TYPE_MASK_CLASS&InputType.TYPE_CLASS_NUMBER)| (InputType.TYPE_MASK_FLAGS & (InputType.TYPE_NUMBER_FLAG_SIGNED |InputType.TYPE_NUMBER_FLAG_DECIMAL))); 

Upvotes: 0

Hiral Vadodaria
Hiral Vadodaria

Reputation: 19250

Try using:

mEditText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);

Edit :

The suggestion i have given above was taken from Doc. but as you said it is not working properly,i can suggest you a more thing.

Add a TextWatcher to your EditText as below,after you set above input type:

mEditText.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3){         

          if(arg0.length()!=0)
          {
                String s=arg0.toString();
                Character c=s.charAt(arg0.length()-1);

                if(c=='/' || c=='\\' || c=='|' || c=='"' || c==':' || c==';' || c=='?' || c=='/' || c==',' || c=='<' || c=='>' || c=='!' || c=='@' || c=='#' || c=='$' || c=='%' || c=='^' || c=='&' || c=='*' || c=='(' || c==')' || c=='_' || c=='=' || c=='+' || c=='-')
                {               
                    if(arg0.length()!=1)
                    {
                        String s1=s.substring(0,arg0.length()-1);
                        mEditText.setText(s1);
                        mEditText.setSelection(s1.length());    
                    }
                    else
                    {
                        mEditText.setText("");
                    }
                }
          }     
    }               
    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
    }               
    @Override
    public void afterTextChanged(Editable arg0) {
    }
}

Upvotes: 4

Lucifer
Lucifer

Reputation: 29642

Please try this,

// TYPE_CLASS_NUMBER: Class for numeric text. This displays the numbers/symbols keyboard.

editText.setInputType(InputType.TYPE_CLASS_NUMBER);

// TYPE_CLASS_PHONE: Class for a phone number. This displays the phone number keypad.

editText.setInputType(InputType.TYPE_CLASS_PHONE);

Upvotes: 0

Related Questions