Home > database >  How to pervent Edittext value To start with (.) and contains two (.) in a row?
How to pervent Edittext value To start with (.) and contains two (.) in a row?

Time:12-15

in my situation i have EditText to get the value for my math operation , So i have set inputType of this EditText to android:inputType="numberSigned" also add this tag android:digits="1234567890." to only get numbers and (.) because my value can be Double , but i don't want the user to start his value with (.) like ".58" also use two (.) in row like "2..5" so i have add the code below but unfortunately it's not working for me. also I'm using TextChangedListener for my EditText.

    public static String trimString(String string) {
    if (string.startsWith(".")) {
        return string.replace(".", "");
    } else if (string.contains(",") & string.contains("..")) {
        return string.replace(",", "").replace("..", ".");
    } else {
        return string;
    }
}

TextChangedListener code:

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

    if (isEmpty(editTextAmount)) {
         tvResult.setTextColor(Color.parseColor("#ff0033"));
         tvResult.setText(R.string.error_text);
      } else {
         String firstData = autoCompleteTextView.getText().toString();
         String secondData = autoCompleteTextView2.getText().toString();
         String amount = trimString(editTextAmount.getText().toString());
         doMath(firstData, secondData, amount);
      }

   }


    

CodePudding user response:

I see you also have another problem. if you use "numberSigned" as the input type you cant use "." character and if you add android:digits="1234567890." there will be no limit of how many times the "." char will appear in your EditText. it can be

..

or

..58

or

2..5

or even

35.67.12

so you see, it's not a number any more.

You can use android:inputType="numberDecimal" instead of numberSigned. This way you only can call "." once in a number (as numbers should be ) and as there is no "," in Decimal numbers user can not use that key even by mistake. so you are already two problems ahead.

As for the "." character at the start of the input, I personally see no problem in that. It is totally OK to have .7 instead of 0.7 but if you want to prevent it you can simply check if it start with "." or not and replace "." with "0."

in conclusion replace the android:inputType="numberSigned" with android:inputType="numberDecimal"; delete the android:digits="1234567890." and you are good to go.

  • Related