软件键盘的android可见性

标签 android android-softkeyboard

我想检查软键盘是否可见。我读过这个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
        }
     }
});

但是activityRootView.getRootView().getHeight()activityRootView.getHeight()总是返回相同的值,不关心键盘是否可见。任何想法为什么?因为这个解决方案似乎适用于其他人。

最佳答案

此代码可能有帮助 -

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;
}

mKeyboardStatus 的默认原始 bool 值将被初始化为 false。

然后按如下方式检查该值,并在必要时执行操作:

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

编辑 -

找出最简单的方法——

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
}
}
});

喜欢这个答案吗?请将其标记为已选择 :).

关于软件键盘的android可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32458374/

相关文章:

android - 在 android 中显示 HTML

android - 过多的字段引用:70613;最大值是65536

android - 单击按钮将 android 键盘语言更改为印地语

java - 在键盘android上添加 View

android - 如何强制以横向模式显示键盘?

android - 在 Sample SoftKeyboard android IME 中看不到候选人

java - 需要帮助显示 Web 服务的 SOAP 请求的返回

Android:如何在顶部滚动 ScrollView

iphone - 手机网站 : Orientation change from portrait to horizontal

android - 在 Listview 中模拟用户对 EditText 的触摸操作