setKeyListener/android:capitalize - Capitalize letters in a TextView using setKeyListener, in Java

How to Capitalize letters in a TextView using setKeyListener, in Java

setKeyListener was added in API Level 1
android:capitalize was added in API Level 1, deprecated in Level 3
** Normally a TextView is not editable though.

Note that for most cases this interface has been superseded by general soft input methods as defined by InputMethod

Sets the key listener to be used with this TextView. This can be null to disallow user input. Note that this method has significant and subtle interactions with soft keyboards and other input method: see KeyListener.getContentType() for important details. Calling this method will replace the current content type of the text view with the content type returned by the key listener.

1. Find a TextView using ID

2. In the MainActivity.java file, add the following the to imports section.
       import android.text.method.TextKeyListener;

3. Add the code below to the onCreate method. This will capitalize all characters by default.

     myTextView.setKeyListener(new TextKeyListener(TextKeyListener.Capitalize.CHARACTERS, true)); 

4. All available options:

* Capitalized all characters by default.
myTextView.setKeyListener(new TextKeyListener(TextKeyListener.Capitalize.CHARACTERS, true));

* Capitalizes the beginning of all words by default.
myTextView.setKeyListener(new TextKeyListener(TextKeyListener.Capitalize.WORDS, true));
* Capitalizes the beginning of sentences by default.
myTextView.setKeyListener(new TextKeyListener(TextKeyListener.Capitalize.SENTENCES, true));

* No default capitalization. Not even for sentences.
myTextView.setKeyListener(new TextKeyListener(TextKeyListener.Capitalize.NONE, true)); 

5. Compile and run!

Related Articles:
Resources: