importandroid.app.Activity;importandroid.os.Build;importandroid.util.Log;importandroid.view.View;importandroid.view.ViewTreeObserver;/*** simple and powerful Keyboard show/hidden listener,view {@android.R.id.content} and {@ViewTreeObserver.OnGlobalLayoutListener}

* Created by yes.cpu@gmail.com 2016/7/13.*/

public class KeyboardChangeListener implementsViewTreeObserver.OnGlobalLayoutListener {private static final String TAG = "ListenerHandler";privateView mContentView;private intmOriginHeight;private intmPreHeight;privateKeyBoardListener mKeyBoardListen;public interfaceKeyBoardListener {/*** call back

*@paramisShow true is show else hidden

*@paramkeyboardHeight keyboard height*/

void onKeyboardChange(boolean isShow, intkeyboardHeight);

}public voidsetKeyBoardListener(KeyBoardListener keyBoardListen) {this.mKeyBoardListen =keyBoardListen;

}publicKeyboardChangeListener(Activity contextObj) {if (contextObj == null) {

Log.i(TAG,"contextObj is null");return;

}

mContentView=findContentView(contextObj);if (mContentView != null) {

addContentTreeObserver();

}

}privateView findContentView(Activity contextObj) {returncontextObj.findViewById(android.R.id.content);

}private voidaddContentTreeObserver() {

mContentView.getViewTreeObserver().addOnGlobalLayoutListener(this);

}

@Overridepublic voidonGlobalLayout() {int currHeight =mContentView.getHeight();if (currHeight == 0) {

Log.i(TAG,"currHeight is 0");return;

}boolean hasChange = false;if (mPreHeight == 0) {

mPreHeight=currHeight;

mOriginHeight=currHeight;

}else{if (mPreHeight !=currHeight) {

hasChange= true;

mPreHeight=currHeight;

}else{

hasChange= false;

}

}if(hasChange) {booleanisShow;int keyboardHeight = 0;if (mOriginHeight ==currHeight) {//hidden

isShow = false;

}else{//show

keyboardHeight = mOriginHeight -currHeight;

isShow= true;

}if (mKeyBoardListen != null) {

mKeyBoardListen.onKeyboardChange(isShow, keyboardHeight);

}

}

}public voiddestroy() {if (mContentView != null) {if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.JELLY_BEAN) {

mContentView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

}

}

}

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐