0

I am not quite familiar in android please help. My problem is I want to remove a dot inside an EditText. In my activity I have one EditText which is set to inputType of numberDecimal. Now when I change it to number the dot in the keypad disappear but in the higher android pf version it appears. By the way I am using android version 2.3.6.

What I did here is set the inputType to decimal and trap the decimal point whenever the user inputted it.

Here's my code:

myEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            String str = s.toString();

            if(s.length() > 0 && s.toString().charAt(s.length() - 1) == '.')
            {
                     showMessage("Decimal numbers is not allowed");
                     CharSequence text = s.subSequence(0, s.length()-1);
                     myEditText.setText(text);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });

Perfectly it removes the dot but the problem right now is the pointer is moving backward and start from the beginning again.

My question how can make the pointer go to front? instead of starting again.

halfer
  • 18,701
  • 13
  • 79
  • 158

1 Answers1

1

to set cursor to end of text

myEditText.setSelection(text.length()); //as you are getting value for text

And I suggest you to put your code to finding "." under afterTextChanged() method. because the official docs says:

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

This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before. It is an error to attempt to make changes to s from this callback.

have a look at official notes:

http://developer.android.com/reference/android/text/TextWatcher.html#afterTextChanged%28android.text.Editable%29

also see similar question android how to set the EditText Cursor to the end of its text

suggesion in code:

use replaceAll to remove the dot

str= str.replaceAll("\\.", "");
            }
Community
  • 1
  • 1
Blue_Alien
  • 1,975
  • 2
  • 20
  • 28