对于仍然面临此问题的任何人,这是 TextWatcher 的方式:
TextWatcher capitalizeTW = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
try{
String inputString = ""+YOUR_TEXT_VIEW.getText().toString();
String firstLetterCapString = WordUtils.capitalize(inputString);
if(!firstLetterCapString.equals(""+YOUR_TEXT_VIEW.getText().toString())){
YOUR_TEXT_VIEW.setText(""+firstLetterCapString);
YOUR_TEXT_VIEW.setSelection(YOUR_TEXT_VIEW.getText().length());
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
};
//将TextWatcher添加到你的TextView
YOUR_TEXT_VIEW.addTextChangedListener(capitalizeTW);
//WordUtils
public final class WordUtils {
private WordUtils(){
}
public static String capitalize(String str) {
return capitalize(str, (char[]) null);
}
public static String capitalize(String str, char... delimiters) {
int delimLen = delimiters == null ? -1 : delimiters.length;
if (!TextUtils.isEmpty(str) && delimLen != 0) {
char[] buffer = str.toCharArray();
boolean capitalizeNext = true;
for (int i = 0; i < buffer.length; ++i) {
char ch = buffer[i];
if (isDelimiter(ch, delimiters)) {
capitalizeNext = true;
} else if (capitalizeNext) {
buffer[i] = Character.toTitleCase(ch);
capitalizeNext = false;
}
}
return new String(buffer);
} else {
return str;
}
}
private static boolean isDelimiter(char ch, char[] delimiters) {
if (delimiters == null) {
return Character.isWhitespace(ch);
} else {
char[] arr$ = delimiters;
int len$ = delimiters.length;
for (int i$ = 0; i$ < len$; ++i$) {
char delimiter = arr$[i$];
if (ch == delimiter) {
return true;
}
}
return false;
}
}
}
我希望这有帮助。