Android软键盘弹出和隐藏事件监听Demo源代码下载
程序员文章站
2022-03-01 14:34:26
...
想实现软键盘的监听、我们必须要自定义View来实现、因为系统提供的状态判断返回值一直是true、无法使用、本Demo利用自定义布局来进行监听、原理是输入法打开时、会对布局造成挤压、这时会调用onLayout方法、因此可以在onLayout中进行判断、运行效果如下
核心代码
public void setOnkeyboarddStateListener( onKeyboardsChangeListener listener) { keyboarddsChangeListener = listener; } // 布局状态发生改变时,会触发onLayout @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (!isInit) { isInit = true; viewHeight = b; keyboardSateChange(KEYBOARD_STATE_INIT); } else { viewHeight = viewHeight < b ? b : viewHeight; } if (isInit && viewHeight > b) { hasKeybord = true; keyboardSateChange(KEYBOARD_STATE_SHOW); Log.w(TAG, "显示软键盘"); } if (isInit && hasKeybord && viewHeight == b) { hasKeybord = false; keyboardSateChange(KEYBOARD_STATE_HIDE); Log.w(TAG, "隐藏软键盘"); } } //切换软键盘状态 public void keyboardSateChange(int state) { if (keyboarddsChangeListener != null) { keyboarddsChangeListener.onKeyBoardStateChange(state); } } //软键盘状态切换监听 public interface onKeyboardsChangeListener { public void onKeyBoardStateChange(int state); }
最后将源代码分享给大家、希望对大家有帮助
源代码下载链接: http://dwtedx.com/download.html?bdkey=s/1i3BYrHz 密码: zebc