2

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?

Siarhei
  • 2,358
  • 3
  • 27
  • 63
  • 1
    There’s no (known that I could find) way to override that. The best bet (and safest from a different-manufacturers-mess-with-android-all-the-time point of view), is a combination of what you are already doing and a text listener to capitalize the first letter of the CharSequence (or when the field loses focus, if that happens for your user case). Consider CapWords too as a flag, if that works (because that one tends to work regardless of the Board switch). But all in all, the best solution is to do both. – Martin Marconcini Aug 08 '17 at 21:08

1 Answers1

1

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.

rumpel
  • 495
  • 9
  • 23
  • Correct me if I am wrong, but this would disable the user from intentionally making the first letter small, ex. deleting the capitalized one and entering a small letter as the firtst? – Sandra Mar 26 '20 at 10:14