Taldakus
Taldakus

Reputation: 715

android visibility of software keyboard

I want to check if the software keyboard is visible. I have read this topic.

final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
        if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
            ... do something here
        }
     }
});

but activityRootView.getRootView().getHeight() and activityRootView.getHeight() always returns the same value, does not care if the keyboard is visible or not. Any ideas why? Because it seems that this solution works for others.

Upvotes: 1

Views: 822

Answers (1)

FadedCoder
FadedCoder

Reputation: 1517

This code might help -

public void dismissKeyboard(){
    InputMethodManager imm =(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(mSearchBox.getWindowToken(), 0);
    mKeyboardStatus = false;
}

public void showKeyboard(){
    InputMethodManager imm =(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    mKeyboardStatus = true;
}

private boolean isKeyboardActive(){
    return mKeyboardStatus;
}

The default primative boolean value for mKeyboardStatus will be initialized to false.

Then check the value as follows, and perform an action if necessary:

mSearchBox.requestFocus();
if(!isKeyboardActive()){
    showKeyboard();
}else{
    dismissKeyboard();
}

EDIT -

The simplest method to find out -

contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
 public void onGlobalLayout() {

Rect r = new Rect();
contentView.getWindowVisibleDisplayFrame(r);
int screenHeight = contentView.getRootView().getHeight();

// r.bottom is the position above soft keypad or device button.
// if keypad is shown, the r.bottom is smaller than that before.
int keypadHeight = screenHeight - r.bottom;

Log.d(TAG, "keypadHeight = " + keypadHeight);

if (keypadHeight > screenHeight * 0.20) { // 0.20 ratio is perhaps enough to determine keypad height.
    // keyboard is opened
}
else {
    // keyboard is closed
}
}
});

Like this answer? Mark this as selected please :).

Upvotes: 6

Related Questions