4

I want to make upper case even if the user write lowercase in edittext.So I am setting ediText text to upper case on addTextChangedListener as per below.

  editText.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s : CharSequence?, start : Int, count : Int, after : Int) {
            }

            override fun onTextChanged(s : CharSequence?, start : Int, before : Int, count : Int) {
                    editText.setText(s.toString().toUpperCase())
            }

            override fun afterTextChanged(s : Editable?) {

            }
    })

But doing this when I type something in editText, app is hanging and I have to kill the app and restart it again.As I want to use this in binding adapter I can't use AllCaps method of xml

Purvesh Dodiya
  • 594
  • 3
  • 17
  • Why dont you use [InputType](https://developer.android.com/reference/android/widget/TextView#attr_android:inputType) method and assign textCapCharacters to it? – Gorks Apr 08 '21 at 17:24
  • 1
    Does this answer your question? [How to capitalize every letter in an Android EditText?](https://stackoverflow.com/questions/13705776/how-to-capitalize-every-letter-in-an-android-edittext) – Cliff Apr 08 '21 at 17:45
  • Welcome to Stackoverflow. I see that you've got a solid problem statement in your question, but your question still needs a few changes if you want to get an answer. Please see [how to ask](https://stackoverflow.com/help/how-to-ask) and update your question appropriately. – Ortund Apr 09 '21 at 06:23

2 Answers2

1

You need to remove the textwatcher before editing the text of the EditText and readd it again when the change is done.

    val watcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            editText.removeTextChangedListener(this)
            editText.setText(s.toString().toUpperCase())
            editText.addTextChangedListener(this)
        }

        override fun afterTextChanged(s: Editable) {}
    }

    editText.addTextChangedListener(watcher)
Zain
  • 37,492
  • 7
  • 60
  • 84
1

You can use the Input type in your xml or programmatically.

editText.inputType == InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS

In your xml you can put

android:inputType="textCapCharacters"

This solution will automatically turn the input to UperCase

Cliff
  • 682
  • 8
  • 30