Android监听软键盘弹出与收起

来源:互联网 发布:开淘宝店铺怎么描述 编辑:程序博客网 时间:2024/06/05 10:18

项目需求,亲测可用。


1. 在EditText的父控件加上

android:focusable="true"android:focusableInTouchMode="true"

2. 设置初始化标志位,免得其他调用干扰

editText = (EditText) view.findViewById(R.id.editText);editText.setOnFocusChangeListener(new View.OnFocusChangeListener(){        public void onFocusChange(View v, boolean hasFocus)        {                if (hasFocus)                {                    init = true;                }        }});


3.  监听界面调整事件

rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){        public void onGlobalLayout()        {                if (init)                {                    if (isKeyboardShown(editText.getRootView()))                    {                        // Do something when keyboard is shown                    }                    else                    {                        // Do something when keyboard is hidden                    }                }        }});


4. 判断事件

private boolean isKeyboardShown(View rootView){        final int SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD = 128;        Rect r = new Rect();        rootView.getWindowVisibleDisplayFrame(r);        int heightDiff = rootView.getBottom() - r.bottom;        return heightDiff > ViewUtils.dpToPixel(SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD);}



0 1