简体   繁体   English

android软件键盘的可见性

[英]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. 但是activityRootView.getRootView().getHeight()activityRootView.getHeight()始终返回相同的值,而不管键盘是否可见。 Any ideas why? 有什么想法吗? Because it seems that this solution works for others. 因为似乎该解决方案适用于其他人。

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. mKeyboardStatus的默认基本布尔值将初始化为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 :). 请将其标记为已selected :)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM