拦截软键盘Android

时间:2017-08-02 09:23:16

标签: android android-softkeyboard

在标题中,我的代码是:

final int MIN_KEYBOARD_HEIGHT_PX = 150;                              // Threshold for minimal keyboard height
    final View decorView = getActivity().getWindow().getDecorView();     // Top-level window decor view

    // Register global layout listener.
    decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        private final Rect windowVisibleDisplayFrame = new Rect();
        private int lastVisibleDecorViewHeight;

        @Override
        public void onGlobalLayout() {
            decorView.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);   // Retrieve visible rectangle inside window
            final int visibleDecorViewHeight = windowVisibleDisplayFrame.height();
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)swipeRefreshLayout.getLayoutParams();
            int marginBottom = (int) context.getResources().getDimension(R.dimen.height_footer);

            if (lastVisibleDecorViewHeight != 0) {
                if (lastVisibleDecorViewHeight > visibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX) {     // Keyboard show
                    params.setMargins(0, 0, 0, 0);
                }
                else if (lastVisibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX < visibleDecorViewHeight) { // Keyboard hide
                    params.setMargins(0, 0, 0, marginBottom);
                }
            }
            swipeRefreshLayout.setLayoutParams(params);
            lastVisibleDecorViewHeight = visibleDecorViewHeight;    // Save current decor view height for the next call
        }
    });

这样可以正常工作,但是如果键盘的大小发生变化,例如从字母数字变为数字,则setMargins不会完全为0,而是使用setMargins(0,0,0,marginBottom)传递第一个案例。

0 个答案:

没有答案