首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >监听android中的键盘显示或隐藏事件

监听android中的键盘显示或隐藏事件
EN

Stack Overflow用户
提问于 2014-06-24 21:54:49
回答 1查看 36.4K关注 0票数 18

我正在尝试侦听显示或隐藏键盘时发生的事件。这在Android中是可能的吗?当我开始我的活动时,我并不想知道键盘是显示的还是隐藏的,我想要监听事件。

EN

回答 1

Stack Overflow用户

发布于 2014-06-24 21:56:46

试试下面的代码:

代码语言:javascript
复制
// 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();
    }
}

代码语言:javascript
复制
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。

代码语言:javascript
复制
@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?

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24388492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档