1

How can I trigger the "shift-button" on the Android keyboard, so that the next character will be capital?

I set the InputType to InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_MULTI_LINE, but this doesn't work if the cursor is anywhere in the line.

I have tried these two methods. Both don't work. The second one throws a RuntimeException ("This method cannot be called from the main application thread"). Maybe because there is no keycode for this button. Is there a way to trigger the button?

0xCursor
  • 2,242
  • 4
  • 15
  • 33
user7174483
  • 73
  • 1
  • 9

1 Answers1

1

EDIT:

It seems that buttons like shift and alt create meta states that affect pressed buttons. From https://developer.android.com/reference/android/view/KeyEvent.html:

Meta states describe the pressed state of key modifiers such as META_SHIFT_ON or META_ALT_ON.

These meta states can be simulated using dispatchKeyEvent like so:

dispatchKeyEvent(new KeyEvent(0,0,KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_L,0,KeyEvent.META_SHIFT_ON));

Were an EditText in focus this would write "L" into it. But it seems that you cannot only send the shift KeyEvent and expect the next character to be uppercase. Perhaps you can come up with some sort of workaround with this.


You're using and EditText, right? For some reason I can't get

dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT));

to work when the EditText is focused while KeyEvents for letters and numbers work.

A workaround could be adding a TextWatcher to the EditText:

editText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            Log.d(TAG, "afterTextChanged: "+s.toString());
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            Log.d(TAG, "beforeTextChanged: "+s.toString());
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.d(TAG, "onTextChanged: "+s.toString());
        }
    });

and checking whether the wanted character of CharSequence s is capitalized in afterTextChanged. If not, then change it to a capitalized version. This is a bit hacky and doesn't quite answer your question I know but unfortunately I'm not able to comment.

batati
  • 180
  • 2
  • 11
  • Thanks for the answer and no problem i am also not able to comment in other threads. Now to your answer. Yes i am using EditText. Is it then not possible to use that dispatchKeyEvent? Because at the moment i do not do anything. The workaroung is not that thing i would to do. But how do Google it in their GoogleDocs-Writer? – user7174483 Mar 02 '17 at 11:43