0

I am making a simple calculator application. I don't want the user to be able to input the multiplication (x) character to be twice or more next to each other. (like xx, xxx, xxx...). Below are the codes I tried.

 int cursorPos=edt_input.getSelectionStart();
  if (edt_input.getText().toString().equals("×")&&cursorPos==0||edt_input.getText().toString().equals("×")&&cursorPos==+1){
        edt_input.setText("");

    }
Ugur Gul
  • 53
  • 9

1 Answers1

0

Use an InputFilter like this

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.isLetter(source.charAt(i)) {
              if (Character.isLetter(source.charAt(i - 1)) {
                  return "";
                }
              }

            }

          };
        }

You can also use the TextWatcher class to get the same functionality

Ref:How to use the TextWatcher class in Android?

myEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // Do nothing
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String str = s.toString();
            if (str.substring(str.length-3,s.length-1)).equals("xx") {
                //put in code to remove the last x via code
            } 
        }

        @Override
        public void afterTextChanged(Editable s) {
            // Do nothing
        }
    });
Narendra_Nath
  • 4,578
  • 3
  • 13
  • 31