vikifor
vikifor

Reputation: 3466

Set letters to upper case dynamically android

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?

Upvotes: 2

Views: 1745

Answers (2)

vguzzi
vguzzi

Reputation: 2428

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"

Upvotes: 3

JBirdVegas
JBirdVegas

Reputation: 11413

Probably easier to just use the Android provided filter

myEditText.setFilters(new InputFilter[] {new InputFilter.AllCaps()});

Upvotes: 1

Related Questions