我正在尝试以编程方式设置“首字母大写”(因为我在ListView
中设置了EditText
)
关于这个问题的话题很多,最著名的是that。我猜。我已经尝试过那里提供的解决方案,并且
setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)
真的很有帮助。异常 - 当用户使用 GBoard
(谷歌键盘) 它没有帮助。 (自动大写未关闭)
那么,是否有可能使其适用于GBoard
?或者也许...当 edittext
中没有文本时,是否可以按编程方式按 shift
?
最佳答案
我在 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) {
}
});
请注意,如果您确实需要在不支持 standard way 的键盘上完成工作,这只是一种解决方法首字母大写。
它将输入的第一个字符大写(忽略数字和特殊字符)。 唯一的缺陷是,键盘(在我们的例子中是 Gboard)的输入仍然显示小写字母。
有关 onTextChanged 参数的详细解释,请参阅 this回答。
关于java - 带有 GBoard 输入的 EditText 首字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45576356/