How to capitalize the first letter of text in a TextView in an Android Application

前端 未结 11 1690
孤街浪徒
孤街浪徒 2020-12-23 15:35

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 Capitaliz

相关标签:
11条回答
  • 2020-12-23 16:20

    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;
    }
    
    0 讨论(0)
  • 2020-12-23 16:22

    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

    0 讨论(0)
  • 2020-12-23 16:24
    StringBuilder sb = new StringBuilder(name);
    sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));  
    return sb.toString();
    
    0 讨论(0)
  • 2020-12-23 16:27

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

    0 讨论(0)
  • 2020-12-23 16:33

    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"
    
    0 讨论(0)
提交回复
热议问题