如何获得软键盘高度/打开/关闭通知

时间:2014-05-08 07:01:34

标签: android

我正面临开发Android应用程序的奇怪场景。 我需要在软键盘打开/关闭时通知我的应用程序的某些组件,并为他们提供键盘高度,以便他们做出相应的反应。 我试过跟随;

getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
        }
});

但它在4.2.2上工作不正常对我来说似乎不合逻辑,因为需要指定布局属性中的离散差异来感知键盘事件。我上网了很多但找不到真正有用的东西。在这方面的任何帮助将受到高度赞赏。

谢谢, 阿马尔

1 个答案:

答案 0 :(得分:0)

很长一段时间后才看到这个问题,但我应该添加我的方法,以便它可能对其他人有所帮助。

首先,我在我的UI中添加了一个不可见的Layout'invisible_layout',以便跟踪大小更新。然后在此OnGlobalLayoutListener上添加Layout以侦听布局更新。调整大小时,Layout的全高和更新用于抢占键盘外观。

int prevViewHeight = 0;

public void keyboardObserver() {
    final View containerView = findViewById(R.id.invisible_layout);

    containerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            if(prevViewHeight != containerView.getHeight()){
                prevViewHeight = containerView.getHeight();

                int heightDiff = containerView.getRootView().getHeight() - containerView.getHeight();
                // heightDiff is the height of the keyboard

                if (heightDiff > heightComparator() ) { // if more than 100 dp, its probably a keyboard...
                    if ( heightDiff > heightComparator() ) {
                        // do what is required on keyboard show
                    } else {
                        // do what is required on keyboard hide
                    }
                }


        }
    });
}

public int heightComparator() {

    Display mDisplay = getWindowManager().getDefaultDisplay();
    int height = 0;
    if(Build.VERSION.SDK_INT < 13){
        height = mDisplay.getHeight();
    } else
    {
        Point size = new Point();
        mDisplay.getSize(size);
        height = size.y;
    }

    return height / 3; // I'm assuming that if the resized height is greate than 1/3 of the screen height, then keyboard is displayed
}

欢迎提出优化建议。

相关问题