我在 Gboard 上遇到了同样的问题并以这种方式解决了它:
final EditText editText = (EditText) findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Check if the entered character is the first character of the input
if(start == 0 && before == 0){
//Get the input
String input = s.toString();
//Capitalize the input (you can also use StringUtils here)
String output = input.substring(0,1).toUpperCase() + input.substring(1);
//Set the capitalized input as the editText text
editText.setText(output);
//Set the cursor at the end of the first character
editText.setSelection(1);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
请注意,如果您确实需要在不支持首字母大写标准方式的键盘上完成工作,这只是一种解决方法。
它将输入的第一个字符大写(忽略数字和特殊字符)。唯一的缺陷是,键盘的输入(在我们的例子中是 Gboard)仍然显示小写字母。
有关 onTextChanged 参数的详细说明,请参阅此答案。