29

i need to change the text="font roboto regular" to Font Roboto Regular in xml itself, how to do?

<TextView
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:gravity="center"
   android:textSize="18sp"
   android:textColor="@android:color/black"
   android:fontFamily="roboto-regular"
   android:text="font roboto regular"
   android:inputType="textCapWords"
   android:capitalize="words"/>
sree
  • 773
  • 2
  • 12
  • 25

15 Answers15

49

If someone looking for kotlin way of doing this, then code becomes very simple and beautiful.

yourTextView.text = yourText.split(' ').joinToString(" ") { it.capitalize() }
Praveena
  • 6,340
  • 2
  • 40
  • 53
40

You can use this code.

String str = "font roboto regular";
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
for (String s : strArray) {
     String cap = s.substring(0, 1).toUpperCase() + s.substring(1);
     builder.append(cap + " ");
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(builder.toString());
Chintan Bawa
  • 1,376
  • 11
  • 15
23

Try this...

Method that convert first letter of each word in a string into an uppercase letter.

 private String capitalize(String capString){
    StringBuffer capBuffer = new StringBuffer();
    Matcher capMatcher = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(capString);
    while (capMatcher.find()){
        capMatcher.appendReplacement(capBuffer, capMatcher.group(1).toUpperCase() + capMatcher.group(2).toLowerCase());
    }

    return capMatcher.appendTail(capBuffer).toString();
}

Usage:

String chars = capitalize("hello dream world");
//textView.setText(chars);
System.out.println("Output: "+chars);

Result:

Output: Hello Dream World
Ankhwatcher
  • 420
  • 6
  • 19
Silambarasan Poonguti
  • 9,386
  • 4
  • 45
  • 38
9

KOTLIN

   val strArrayOBJ = "Your String".split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                val builder = StringBuilder()
                for (s in strArrayOBJ) {
                    val cap = s.substring(0, 1).toUpperCase() + s.substring(1)
                    builder.append("$cap ")
                }
txt_OBJ.text=builder.toString()
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
5

Modification on the accepted answer to clean out any existing capital letters and prevent the trailing space that the accepted answer leaves behind.

public static String capitalize(@NonNull String input) {

    String[] words = input.toLowerCase().split(" ");
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < words.length; i++) {
        String word = words[i];

        if (i > 0 && word.length() > 0) {
            builder.append(" ");
        }

        String cap = word.substring(0, 1).toUpperCase() + word.substring(1);
        builder.append(cap);
    }
    return builder.toString();
}
Ankhwatcher
  • 420
  • 6
  • 19
4

you can use this method to do it programmatically

public String wordFirstCap(String str)
{
    String[] words = str.trim().split(" ");
    StringBuilder ret = new StringBuilder();
    for(int i = 0; i < words.length; i++)
    {
        if(words[i].trim().length() > 0)
        {
            Log.e("words[i].trim",""+words[i].trim().charAt(0));
            ret.append(Character.toUpperCase(words[i].trim().charAt(0)));
            ret.append(words[i].trim().substring(1));
            if(i < words.length - 1) {
                ret.append(' ');
            }
        }
    }

    return ret.toString();
}

refer this if you want to do it in xml.

Community
  • 1
  • 1
Ravi
  • 34,851
  • 21
  • 122
  • 183
3

You can use

private String capitalize(final String line) {
   return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}

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

Community
  • 1
  • 1
Anjali Tripathi
  • 1,477
  • 9
  • 28
1

android:capitalize is deprecated.

Follow these steps: https://stackoverflow.com/a/31699306/4409113

  1. Tap icon of ‘Settings’ on the Home screen of your Android Lollipop Device
  2. At the ‘Settings’ screen, scroll down to the PERSONAL section and tap the ‘Language & input’ section.
  3. At the ‘Language & input’ section, select your keyboard(which is marked as current keyboard).
  4. Now tap the ‘Preferences’.
  5. Tap to check the ‘Auto – Capitalization’ to enable it.

And then it should work.

If it didn't, i'd rather to do that in Java.

Community
  • 1
  • 1
ʍѳђઽ૯ท
  • 16,646
  • 7
  • 53
  • 108
1

Another approach is to use StringTokenizer class. The below method works for any number of words in a sentence or in the EditText view. I used this to capitalize the full names field in an app.

public String capWordFirstLetter(String fullname)
{
    String fname = "";
    String s2;
    StringTokenizer tokenizer = new StringTokenizer(fullname);
    while (tokenizer.hasMoreTokens())
    {
        s2 = tokenizer.nextToken().toLowerCase();
        if (fname.length() == 0)
            fname += s2.substring(0, 1).toUpperCase() + s2.substring(1);
        else
            fname += " "+s2.substring(0, 1).toUpperCase() + s2.substring(1);
    }

    return fname;
}
Ankhwatcher
  • 420
  • 6
  • 19
Cletus Ajibade
  • 1,550
  • 15
  • 14
1

https://stackoverflow.com/a/1149869/2725203

Have a look at ACL WordUtils.

WordUtils.capitalize("your string") == "Your String"

Community
  • 1
  • 1
1

in kotlin, string extension

fun String?.capitalizeText() = (this?.toLowerCase(Locale.getDefault())?.split(" ")?.joinToString(" ") { if (it.length <= 1) it else it.capitalize(Locale.getDefault()) }?.trimEnd())?.trim()
Jonnys J.
  • 111
  • 1
  • 2
0

Kotlin extension function for capitalising each word

val String?.capitalizeEachWord
    get() = (this?.lowercase(Locale.getDefault())?.split(" ")?.joinToString(" ") {
        if (it.length <= 1) it else it.replaceFirstChar { firstChar ->
            if (firstChar.isLowerCase()) firstChar.titlecase(
                Locale.getDefault()
            ) else firstChar.toString()
        }
    }?.trimEnd())?.trim()
Eldhopj
  • 2,703
  • 3
  • 20
  • 39
0

As the best way for achieving this used to be the capitalize() fun, but now it got depricated in kotlin. So we have an alternate for this. I've the use case where I'm getting a key from api that'll be customized at front end & will be shown apparently. The value is coming as "RECOMMENDED_OFFERS" which should be updated to be shown as "Recommended Offers". I've created an extension function :

fun String.updateCapitalizedTextByRemovingUnderscore(specialChar: String): String

that takes a string which need to be replaced with white space (" ") & then customise the words as their 1st character would be in caps. So, the function body looks like :

fun String.updateCapitalizedTextByRemovingUnderscore(
 specialChar: String  = "") : String {
 var tabName = this
  // removing the special character coming in parameter & if 
     exist
  if (spclChar.isNotEmpty() && this.contains(specialChar)) {
      tabName = this.replace(spclChar, " ")
  }
  return tabName.lowercase().split(' ').joinToString(" ") {
      it.replaceFirstChar { if (it.isLowerCase()) 
      it.titlecase(Locale.getDefault()) else it.toString() } }
}

How to call the extension function :

textView.text = 
 "RECOMMENDED_OFFERS".updateCapitalizedTextByRemovingUnderscore("_")

OR textView.text = <api_key>.updateCapitalizedTextByRemovingUnderscore("_")

The desired output will be : Recommended Offers

Hope this will help.Happy coding :) Cheers!!

Abhijeet
  • 501
  • 4
  • 7
0

capitalize each word

 public static String toTitleCase(String string) {

    // Check if String is null
    if (string == null) {
        
        return null;
    }

    boolean whiteSpace = true;
    
    StringBuilder builder = new StringBuilder(string); // String builder to store string
    final int builderLength = builder.length();

    // Loop through builder
    for (int i = 0; i < builderLength; ++i) {

        char c = builder.charAt(i); // Get character at builders position
        
        if (whiteSpace) {
            
            // Check if character is not white space
            if (!Character.isWhitespace(c)) {
                
                // Convert to title case and leave whitespace mode.
                builder.setCharAt(i, Character.toTitleCase(c));
                whiteSpace = false;
            }
        } else if (Character.isWhitespace(c)) {
            
            whiteSpace = true; // Set character is white space
        
        } else {
        
            builder.setCharAt(i, Character.toLowerCase(c)); // Set character to lowercase
        }
    }

    return builder.toString(); // Return builders text
}

use String to txt.setText(toTitleCase(stringVal))

don't use android:fontFamily to roboto-regular. hyphen not accept. please rename to roboto_regular.

-3

To capitalize each word in a sentence use the below attribute in xml of that paticular textView.

android:inputType="textCapWords"

Er Prajesh
  • 61
  • 1
  • 5
  • 1
    This cannot be used inside TextView. This is for EditText only. Check Android warning for more information.' – ralphgabb Apr 23 '19 at 14:33