Java – How to complete () an activity using the SoftKeyboard visible using onBackPressed().

How to complete () an activity using the SoftKeyboard visible using onBackPressed()…. here is a solution to the problem.

How to complete () an activity using the SoftKeyboard visible using onBackPressed().

I have an activity where the entire screen is dedicated to sending a message. As an EditText in the upper half, the SoftKeyboard is always visible in the lower half.
When I press the back key, the SoftKeyboard hides and I have to press the back key again to leave the activity.

The behavior I’m trying to get is that the activity is completed immediately when I press the back button, rather than hiding the keyboard.
For example, when writing a new tweet, you can find this behavior in the Twitter app.

I tried to override the onBackPressed() function, but it seems that when the keyboard is visible, the function is not called.

@Override
public void onBackPressed() {
     finish();
}

Thanks a lot for any help!

Solution

So after trying a lot of things, here are some useful things:

Inherit the EditText and override the onKeyPreIme() function to send a callback.
Here is the code for the subclass:

OnKeyPreImeListener onKeyPreImeListener;

public void setOnKeyPreImeListener(OnKeyPreImeListener onKeyPreImeListener) {
    this.onKeyPreImeListener = onKeyPreImeListener;
}

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
        if(onKeyPreImeListener != null)
            onKeyPreImeListener.onBackPressed();
        Log.d(TAG, "HIDING KEYBOARD");
        return false;
    }
    return super.dispatchKeyEvent(event);
}

public interface OnKeyPreImeListener {
    void onBackPressed();
}

Then in each of your TextView activities:

EditTextGraphee.OnKeyPreImeListener onKeyPreImeListener = 
        new EditTextGraphee.OnKeyPreImeListener() {
        @Override
        public void onBackPressed() {
            Log.d(TAG, "CALL BACK RECEIVED");
            MyActivity.this.onBackPressed();
        }
    };
editText.setOnKeyPreImeListener(onKeyPreImeListener);

Related Problems and Solutions