117

I'm not referring to textInput, either. I mean that once you have static text in a TextView (populated from a Database call to user inputted data (that may not be Capitalized)), how can I make sure they are capitalized?

Thanks!

Gene Bo
  • 11,284
  • 8
  • 90
  • 137
Allen Gingrich
  • 5,608
  • 10
  • 45
  • 57

21 Answers21

218

I should be able to accomplish this through standard java string manipulation, nothing Android or TextView specific.

Something like:

String upperString = myString.substring(0, 1).toUpperCase() + myString.substring(1).toLowerCase();

Although there are probably a million ways to accomplish this. See String documentation.

EDITED I added the .toLowerCase()

Hrk
  • 2,725
  • 5
  • 29
  • 44
Cheryl Simon
  • 46,552
  • 15
  • 93
  • 82
84

Following does not apply to TextView, but works with EditText; even then, it applies to the text entered from the keyboard, not the text loaded with setText(). To be more specific, it turns the Caps on in the keyboard, and the user can override this at her will.

android:inputType="textCapSentences"

or

TV.sname.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

This will CAP the first letter.

or

compile 'org.apache.commons:commons-lang3:3.4' //in build.gradle module(app)

tv.setText(StringUtils.capitalize(myString.toLowerCase().trim()));
Shubham AgaRwal
  • 4,355
  • 8
  • 41
  • 62
Beto Caldas
  • 2,198
  • 2
  • 23
  • 23
  • 82
    This does not apply to TextView, but only to EditText; even then, it applies to text entered from keyboard, not the text loaded with setText(). To be more specific, it turns the Caps on in the keyboard, and the user can override this at her will. – Alex Cohn Feb 17 '15 at 08:09
35

for Kotlin, just call

textview.text = string.capitalize()
Ben Kax
  • 446
  • 4
  • 3
34
StringBuilder sb = new StringBuilder(name);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));  
return sb.toString();
noloman
  • 11,411
  • 20
  • 82
  • 129
10

You can add Apache Commons Lang in Gradle like compile 'org.apache.commons:commons-lang3:3.4'

And use WordUtils.capitalizeFully(name)

Prakash
  • 4,479
  • 30
  • 42
  • 1
    info: lang3 WordUtils is deprecated, you should use "org.apache.commons.text.WordUtils" instead: https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/WordUtils.html#capitalizeFully(java.lang.String) – gabhor Dec 10 '18 at 13:52
4

For future visitors, you can also (best IMHO) import WordUtil from Apache and add a lot of useful methods to you app, like capitalize as shown here:

How to capitalize the first character of each word in a string

Community
  • 1
  • 1
Androiderson
  • 16,865
  • 6
  • 62
  • 72
4

For me none of working:

Function:

private String getCapsSentences(String tagName) {
    String[] splits = tagName.toLowerCase().split(" ");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < splits.length; i++) {
        String eachWord = splits[i];
        if (i > 0 && eachWord.length() > 0) {
            sb.append(" ");
        }
        String cap = eachWord.substring(0, 1).toUpperCase() 
                + eachWord.substring(1);
        sb.append(cap);
    }
    return sb.toString();
}

Result:

I/P brain O/P Brain

I/P Brain and Health O/P Brain And Health

I/P brain And health to O/P Brain And Health

I/P brain's Health to O/P Brain's Health

I/P brain's Health and leg to O/P Brain's Health And Leg

Hope this would help you.

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
4

For Kotlin, if you want to be sure that the format is "Aaaaaaaaa" you can use :

myString.toLowerCase(Locale.getDefault()).capitalize()
VinceMedi
  • 210
  • 2
  • 8
3

The accepted answer is good, but if you are using it to get values from a textView in android, it would be good to check if the string is empty. If the string is empty it would throw an exception.

private String capitizeString(String name){
    String captilizedString="";
    if(!name.trim().equals("")){
       captilizedString = name.substring(0,1).toUpperCase() + name.substring(1);
    }
    return captilizedString;
}
Sidharth V
  • 117
  • 8
3

Note that Kotlin's .capitalize() is deprecated as of 1.5 as it isn't locale friendly. The suggestion is to use .replaceFirstChar()

Android Studio warns me

Implicitly using the default locale is a common source of bugs: Use capitalize(Locale) instead. For strings meant to be internal use Locale.ROOT, otherwise Locale.getDefault().

Thanks to the built in autofix, I made this extension function

fun String.titlecase(): String =
    this.replaceFirstChar { // it: Char
        if (it.isLowerCase())
            it.titlecase(Locale.getDefault())
        else
            it.toString()
    }
Jay Wick
  • 12,325
  • 10
  • 54
  • 78
  • 1
    Kotlin [release docs](https://kotlinlang.org/docs/whatsnew15.html#stable-locale-agnostic-api-for-upper-lowercasing-text) say use `String.replaceFirstChar { it.uppercase() }` as alternative. it uses `Locale.ROOT` – P Kuijpers Jun 08 '21 at 15:48
2

Add Kotlin Extension

fun String.firstCap()=this.replaceFirstChar { it.uppercase() }

Usecase

"lowercase letter".firstCap() //gives "Lowercase letter"
Ngima Sherpa
  • 1,397
  • 1
  • 13
  • 34
1

Please create a custom TextView and use it :

public class CustomTextView extends TextView {

    public CapitalizedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        if (text.length() > 0) {
            text = String.valueOf(text.charAt(0)).toUpperCase() + text.subSequence(1, text.length());
        }
        super.setText(text, type);
    }
}
Mike
  • 4,550
  • 4
  • 33
  • 47
Shrini Jaiswal
  • 1,090
  • 12
  • 12
  • how do I make this CustomTextView to be appeared in Design of Activity/Fragments as drag and drop UI element? – Kostanos Feb 19 '19 at 16:01
1

Here I have written a detailed article on the topic, as we have several options, Capitalize First Letter of String in Android

Method to Capitalize First Letter of String in Java

public static String capitalizeString(String str) {
        String retStr = str;
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
        }catch (Exception e){}
        return retStr;
}

Method to Capitalize First Letter of String in Kotlin

fun capitalizeString(str: String): String {
        var retStr = str
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
        } catch (e: Exception) {
        }
        return retStr
}

Using XML Attribute

Or you can set this attribute in TextView or EditText in XML

android:inputType="textCapSentences"
Asad Ali Choudhry
  • 4,985
  • 4
  • 31
  • 36
1

For those using Jetpack Compose, you should use Compose's String.capitalize(locale: Locale), instead of Kotlin's, as follows:

import androidx.compose.ui.text.capitalize
import androidx.compose.ui.text.intl.Locale
    
Text("my text".capitalize(Locale.current)) // capitalizes first letter
Text("my text".toUpperCase(Locale.current)) // all caps
Mauro Banze
  • 1,898
  • 15
  • 11
1

by using below property

android:inputType="textCapSentences|textCapWords"
Atif AbbAsi
  • 5,633
  • 7
  • 26
  • 47
0

These lines of code helped me

String[] message_list=message.split(" ");
    String full_message="";

    for (int i=0; i<message_list.length; i++)
    {
        StringBuilder sb = new StringBuilder(message_list[i]);
        sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
        full_message=full_message+" "+sb;
    }

    textview_message.setText(full_message);
Basant
  • 741
  • 7
  • 16
0

In Android XML this can be done with data-binding.

Once enabled in the build.gradle:

android {
    buildFeatures {
        dataBinding = true
    }
}

One can use it to generate data-bindings from XML, which do permit simple code statements:

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <import type="java.util.Locale"/>
    </data>

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical">

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/role"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text='@{ user.role != null ? user.role.substring(0, 1).toUpperCase(Locale.getDefault()) + user.role.substring(1) : "n/a" }'
            android:gravity="center_vertical"
            android:textSize="12sp"/>

    </androidx.appcompat.widget.LinearLayoutCompat>

</layout>

Obviously, one could as well import Kotlin or JetPack Compose classes ...

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
0
//Capitalize the first letter of the words
public String Capitalize(String str) {
    String[] arr = str.split(" "); //convert String to StringArray
    StringBuilder stringBuilder = new StringBuilder();

    for (String w : arr) {
        if (w.length() > 1) {
            stringBuilder.append(w.substring(0, 1).toUpperCase(Locale.US) + w.substring(1).toLowerCase(Locale.US) + " ");
        }
    }
    return stringBuilder.toString().trim();
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 25 '22 at 14:48
0
fun TextView.capitalizeWords() {
    text = text.split(" ").joinToString(" ") { it.replaceFirstChar { char -> char.uppercaseChar() } }
}
0

Update 2023 June, Use this Extension

fun String.toTitleCase() = replaceFirstChar { text -> if (text.isLowerCase()) text.titlecase(
Locale.getDefault()) else text.toString() }
-1

With Kotlin:

textview.text = string.replaceFirstChar(Char::uppercase)
francis
  • 3,852
  • 1
  • 28
  • 30