android - 在android中监听键盘显示或隐藏事件

标签 android listener android-softkeyboard

我正在尝试监听键盘显示或隐藏时发生的事件。这在Android中可能吗?当我开始我的 Activity 时,我不想弄清楚键盘是显示还是隐藏,我想听事件。

最佳答案

试试下面的代码:-

// from the link above
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);


    // Checks whether a hardware keyboard is available
    if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
        Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
    } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
        Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
    }
}

boolean isOpened = false;

 public void setListnerToRootView(){
    final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content); 
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
            if (heightDiff > 100 ) { // 99% of the time the height diff will be due to a keyboard.
                Toast.makeText(getApplicationContext(), "Gotcha!!! softKeyboardup", 0).show();

                if(isOpened == false){
                    //Do two things, make the view top visible and the editText smaller
                }
                isOpened = true;
            }else if(isOpened == true){
                Toast.makeText(getApplicationContext(), "softkeyborad Down!!!", 0).show();                  
                isOpened = false;
            }
         }
    });
}

对于以下代码,您必须扩展 LinearLayout。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
    final int actualHeight = getHeight();

    if (actualHeight > proposedheight){
        // Keyboard is shown
    } else {
        // Keyboard is hidden
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

见以下链接:-

How to capture the "virtual keyboard show/hide" event in Android?

关于android - 在android中监听键盘显示或隐藏事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24388492/

相关文章:

java - android编程使用onsaveinstancestate保存数组

android - 访问 wifi.getScanResults() 中的结果时发生崩溃

Java 事件监听器 - 检测 JMenu 何时打开

kotlin - 单元测试Kotlin的ConflatedBroadcastChannel行为

android - 如何在android中的键盘上方添加保存和取消按钮

android - 仅适用于手机的软键盘未显示在 AlertDialog 中

java - RSA加密Android和Java中的解密: javax. crypto.BadPaddingException:解密错误

安卓 HCE : are there rules for AID?

Android Smack 4.1 没有调用连接监听器

android - SoftKeyboard 隐藏 EditText