I'm trying to set up "First letter capitalization" progrommaticaly (because I have set of EditText
in ListView
)
There is a lot of topic related to this issue, and the most famous is that I guess. I've tried solutions provided there and
setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)
really helps. Exception - when user use GBoard
(google keyboard) it dosen't help. (Auto-capitalization not switched off)
So, is it possible to make it working for GBoard
? or maybe... is it possible to press shift
progrommatically when there is no text in edittext
?
I had the same problem with Gboard and solved it this way:
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) {
}
});
Note, that this is only a workaround if you really need to get the job done on keyboards that won't support the standard way of capitalizing the first letter.
It capitalizes the first character of the input (digits and special chars are ignored). The only flaw is, that the input of the keyboard (in our case Gboard) still shows the lower case letters.
For a great explanation of the onTextChanged parameters see this answer.