Tal*_*kus 1 android android-softkeyboard
我想检查软件键盘是否可见.我读过这个 话题.
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
}
}
});
Run Code Online (Sandbox Code Playgroud)
但是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;
}
Run Code Online (Sandbox Code Playgroud)
mKeyboardStatus的默认原始布尔值将初始化为false.
然后按如下方式检查值,并在必要时执行操作:
mSearchBox.requestFocus();
if(!isKeyboardActive()){
showKeyboard();
}else{
dismissKeyboard();
}
Run Code Online (Sandbox Code Playgroud)
编辑 -
找出最简单的方法 -
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
}
}
});
Run Code Online (Sandbox Code Playgroud)
喜欢这个答案?selected请将此标记为:).
| 归档时间: |
|
| 查看次数: |
675 次 |
| 最近记录: |