2

I like every time user enter a letter into edit text, to convert the letter into upper case. Here is my code:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    test = (EditText) findViewById(R.id.test);
    test.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            beforeStr = s.toString();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
                char current = s.charAt(before);
                newCurrent += String.valueOf(current).toUpperCase() + beforeStr;
        }

        @Override
        public void afterTextChanged(Editable s) {
            test.setText(newCurrent);
        }
    });
}

setText method calls again and again all the methods from TextWatcher and my converting never ends.

Could somebody help me?

vikifor
  • 3,426
  • 4
  • 45
  • 75

2 Answers2

3

You need to make sure you check if your text is upper case before changing it. This way it won't change it again if it doesn't have to and put you into a continuous loop. You don't need to put anything inside beforeTextChanged and afterTextChanged.

Example:

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    String upper = s.toString().toUpperCase();
    if (!s.equals(upper)) {
        test.setText(upper);
    }
}

Or you could simply add this line in your EditText xml.

android:textAllCaps="true"
vguzzi
  • 2,420
  • 2
  • 15
  • 19
  • 1
    You never want to use `==` or `!=` for String equality. This compares the objects not the values. Instead you always want to use `String#equals` for String equality. In the above code `if (s != upper) {` will always be true as a `CharSequence` object will never equal a `String` object even if they hold the same exact Characters. – JBirdVegas Oct 18 '15 at 02:37
1

Probably easier to just use the Android provided filter

myEditText.setFilters(new InputFilter[] {new InputFilter.AllCaps()});
JBirdVegas
  • 10,855
  • 2
  • 44
  • 50