2010-08-05 22 views

回答

98

我应该能够通过标准的java字符串操作来完成这个任务,没有特定的Android或TextView。

喜欢的东西:

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

虽然有可能是一百万的方式来做到这一点。请参阅String文档。

+4

只是想要指出,这是一个很好的解决方案,但不适合本地化。 – 2016-05-16 15:28:07

+0

花了一小部分......谢谢,队友... – 2017-12-03 12:56:09

13
StringBuilder sb = new StringBuilder(name); 
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); 
return sb.toString(); 
47
android:inputType="textCapSentences" 

TV.sname.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); 

这将CAP CAP的第一个字母。

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

tv.setText(StringUtils.capitalize(myString.toLowerCase().trim())); 
+1

这已经帮了很多! – 2015-01-08 15:15:18

+49

这不适用于TextView,但仅适用于EditText;即使如此,它适用于从键盘输入的文本,而不是使用setText()加载的文本。更具体地说,它将键盘上的Caps打开,并且用户可以按照她的意愿覆盖它。 – 2015-02-17 08:09:41

4

您可以在摇篮中添加Apache Commons Langcompile 'org.apache.commons:commons-lang3:3.4'

并使用WordUtils.capitalizeFully(name)

1

请创建一个自定义的TextView并使用它:

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

只需在EditText XML中添加此属性:android:inputType="textCapWords"这将限制插入所有单词的第一个字母

+0

为什么不能在Android Studio中预览xml文件。 – toobsco42 2018-03-02 21:25:18

相关问题