2010-08-05 21 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

相關問題