sree
sree

Reputation: 783

How to change First letter of each word to Uppercase in Textview xml

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"/>

Upvotes: 29

Views: 63454

Answers (15)

muhammed faisal v.v
muhammed faisal v.v

Reputation: 21

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.

Upvotes: 0

Abhijeet
Abhijeet

Reputation: 601

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!!

Upvotes: 0

Eldhopj
Eldhopj

Reputation: 3579

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()

Upvotes: 0

QuanticHeart
QuanticHeart

Reputation: 121

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()

Upvotes: 1

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

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()

Upvotes: 9

Ankhwatcher
Ankhwatcher

Reputation: 420

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();
}

Upvotes: 5

Praveena
Praveena

Reputation: 6941

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

yourTextView.text = yourText.split(' ').joinToString(" ") { it.capitalize() }

Upvotes: 52

Er Prajesh
Er Prajesh

Reputation: 61

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

android:inputType="textCapWords"

Upvotes: -3

Silambarasan Poonguti
Silambarasan Poonguti

Reputation: 9442

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

Upvotes: 23

Cletus Ajibade
Cletus Ajibade

Reputation: 1590

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;
}

Upvotes: 1

saman shoja
saman shoja

Reputation: 11

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

Have a look at ACL WordUtils.

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

Upvotes: 1

Anjali Tripathi
Anjali Tripathi

Reputation: 1477

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

Upvotes: 3

ʍѳђઽ૯ท
ʍѳђઽ૯ท

Reputation: 16976

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.

Upvotes: 1

Ravi
Ravi

Reputation: 35569

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.

Upvotes: 4

Chintan Bawa
Chintan Bawa

Reputation: 1386

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());

Upvotes: 40

Related Questions