runOnUIThread on android is unable to setfocus on the EditText and show soft keyboard

84 Views Asked by At

In my android application, the core logic is written in C++. Hence, for multiple scenarios, there will be JNI calls happening.

In one use-case, as the text is being entered by the user in the 'EditText', I call a JNI method which will capitalize each word (the logic and hence the outcome can vary from case to case).

The TextChange handler calls a JNI function which will capitalize each word in the text in a worker thread and then invoke a method on the main thread using 'runOnUIThread' to update the text field's value. My expectation is this should happen seamlessly and should not hamper the way the user is interacting.

Code Samples:

Calling of the JNI function-

edittext.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                
                OnTextChanged (edittext.getId(), String.valueOf(s));
            }
            ...
     });

Updating the EditText with the capitalized text-

// Below function is invoked on the Main Thread once the Worker Thread is done with its job of capitalizing
// An entry function is called which gets the textfield object from the layout and then called the below
public static void UpdateTextField(EditText pEditTextObj, int pID, int pPosX, int pPosY, int pHeight, int pWidth, int pColor, String pText)
{
        Log.d("SampleJNIApp01", "TextField valued to be updated = " + pText);
        
        pEditTextObj.setText(pText);

        //requesting focus
        pEditTextObj.requestFocus();
        pEditTextObj.setSelection(pEditTextObj.getText().length());

        //showing keyboard
        InputMethodManager imm = (InputMethodManager) MainActivity.GetCurrentActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(pEditTextObj, InputMethodManager.SHOW_IMPLICIT);
         
}

Observation:

Once the first letter is typed in, it does get capitalized by the JNI function and the text in the EditText is also updated.

However, after the pEditTextObj.setText(pText), the focus goes away, cursor is not visible and the keyboard gets hidden.

Same is observed when I am typing in the text field and some worker thread has invoked some java method to 'runOnUIthread' - the focus is lost and soft keyboard gets hidden.

The returned value of pEditTextObj.requestFocus() is true, still it is not getting focussed.

I have also checked that pEditTextObj.isFocusable() returns true and MainActivity.this.getCurrentFocus() is returning the same edittext. but on the emulator screen the edittext is not getting focused neither the keyboard is poping up.

Is there something wrong that I am doing ?

1

There are 1 best solutions below

2
Byte Code On

Try putting some delay beetween requestFocus and showKeyboard functions. I had the same problem before and it worked for me.