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
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;
}
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
StringBuilder sb = new StringBuilder(name);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
return sb.toString();
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()
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"