Created
September 12, 2017 03:59
-
-
Save xingstarx/7a535fdda432e7678b53c628099c96ab to your computer and use it in GitHub Desktop.
监听软键盘是否开启或者关闭
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* https://pspdfkit.com/blog/2016/keyboard-handling-on-android/ | |
* 监听软键盘变化(针对full screen model) | |
*/ | |
public class KeyBoardChangeListener implements ViewTreeObserver.OnGlobalLayoutListener { | |
private static final String TAG = "KeyBoardChangeListener"; | |
// Threshold for minimal keyboard height. | |
final int MIN_KEYBOARD_HEIGHT_PX = 150; | |
private final Rect windowVisibleDisplayFrame = new Rect(); | |
// Top-level window decor view. | |
private View decorView; | |
private int lastVisibleDecorViewHeight; | |
private KeyBoardListener keyBoardListener; | |
KeyBoardChangeListener(Activity activity) { | |
if (activity == null) { | |
Log.e(TAG, "activity is null"); | |
return; | |
} | |
decorView = activity.getWindow().getDecorView(); | |
decorView.getViewTreeObserver().addOnGlobalLayoutListener(this); | |
} | |
public void setKeyBoardListener(KeyBoardListener keyBoardListener) { | |
this.keyBoardListener = keyBoardListener; | |
} | |
@Override | |
public void onGlobalLayout() { | |
// Retrieve visible rectangle inside window. | |
decorView.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame); | |
final int visibleDecorViewHeight = windowVisibleDisplayFrame.height(); | |
// Decide whether keyboard is visible from changing decor view height. | |
if (lastVisibleDecorViewHeight != 0) { | |
if (lastVisibleDecorViewHeight > visibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX) { | |
// Calculate current keyboard height (this includes also navigation bar height when in fullscreen mode). | |
int currentKeyboardHeight = decorView.getHeight() - windowVisibleDisplayFrame.bottom; | |
// Notify listener about keyboard being shown. | |
if (keyBoardListener != null) { | |
keyBoardListener.onKeyboardChange(true, currentKeyboardHeight); | |
} | |
} else if (lastVisibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX < visibleDecorViewHeight) { | |
// Notify listener about keyboard being hidden. | |
if (keyBoardListener != null) { | |
keyBoardListener.onKeyboardChange(false, 0); | |
} | |
} | |
} | |
// Save current decor view height for the next call. | |
lastVisibleDecorViewHeight = visibleDecorViewHeight; | |
} | |
public interface KeyBoardListener { | |
/** | |
* call back | |
* | |
* @param isShow true is show else hidden | |
* @param keyboardHeight keyboard height | |
*/ | |
void onKeyboardChange(boolean isShow, int keyboardHeight); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
用法如下:(kotlin)