今天看到网上一个关于android监听键盘弹起的功能,写了这篇文章记录下
KeyboardChangeListener,主要代码:
| public class KeyboardChangeListener implements ViewTreeObserver.OnGlobalLayoutListener { |
| private static final String TAG = "ListenerHandler"; |
| private View mContentView; |
| private int mOriginHeight; |
| private KeyBoardListener mKeyBoardListen; |
| public interface KeyBoardListener { |
| * @param isShow true is show else hidden |
| * @param keyboardHeight keyboard height |
| void onKeyboardChange(boolean isShow, int keyboardHeight); |
| public void setKeyBoardListener(KeyBoardListener keyBoardListen) { |
| this.mKeyBoardListen = keyBoardListen; |
| public KeyboardChangeListener(Activity contextObj) { |
| if (contextObj == null) { |
| Log.i(TAG, "contextObj is null"); |
| mContentView = findContentView(contextObj); |
| if (mContentView != null) { |
| addContentTreeObserver(); |
| private View findContentView(Activity contextObj) { |
| return contextObj.findViewById(android.R.id.content); |
| private void addContentTreeObserver() { |
| mContentView.getViewTreeObserver().addOnGlobalLayoutListener(this); |
| public void onGlobalLayout() { |
| int currHeight = mContentView.getHeight(); |
| Log.i(TAG, "currHeight is 0"); |
| boolean hasChange = false; |
| mOriginHeight = currHeight; |
| if (mPreHeight != currHeight) { |
| if (mOriginHeight == currHeight) { |
| keyboardHeight = mOriginHeight - currHeight; |
| if (mKeyBoardListen != null) { |
| mKeyBoardListen.onKeyboardChange(isShow, keyboardHeight); |
| if (mContentView != null) { |
| if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { |
| mContentView.getViewTreeObserver().removeOnGlobalLayoutListener(this); |
}