本文基于stackoverflow上提供的SoftKeyboardStateHelper类的改进,主要用与解决某些型号手机(如华为)上监听不正确的情况,
原文地址: http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android
具体代码如下:
public class SoftKeyboardStateHelper implements OnGlobalLayoutListener {
public interface SoftKeyboardStateListener {
void onSoftKeyboardOpened(int keyboardHeightInPx);
void onSoftKeyboardHidden();
}
private final List<SoftKeyboardStateListener> listeners = new LinkedList<SoftKeyboardStateListener>();
private final View activityRootView;
private int lastSoftKeyboardHeightInPx;
private int baseDiffHeight = 0;
private boolean isSoftKeyboardOpened;
public SoftKeyboardStateHelper(View activityRootView) {
this(activityRootView, false);
}
public SoftKeyboardStateHelper(View activityRootView, boolean isSoftKeyboardOpened) {
this.activityRootView = activityRootView;
this.isSoftKeyboardOpened = isSoftKeyboardOpened;
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(this);
}
@Override
public void onGlobalLayout() {
final Rect rect = new Rect();
activityRootView.getWindowVisibleDisplayFrame(rect);
final int heightDiff = activityRootView.getRootView().getHeight() - (rect.bottom - rect.top);
if (baseDiffHeight<=0) {
baseDiffHeight = heightDiff;
}
if (!isSoftKeyboardOpened && heightDiff > (baseDiffHeight+100)) { // if more than 100 pixels, its probably a keyboard...
isSoftKeyboardOpened = true;
notifyOnSoftKeyboardOpened(heightDiff-baseDiffHeight);
} else if (isSoftKeyboardOpened && heightDiff < (baseDiffHeight+100)) {
isSoftKeyboardOpened = false;
notifyOnSoftKeyboardHidden();
}
}
public void setIsSoftKeyboardOpened(boolean isSoftKeyboardOpened) {
this.isSoftKeyboardOpened = isSoftKeyboardOpened;
}
public boolean isSoftKeyboardOpened() {
return isSoftKeyboardOpened;
}
/**
* Default value is zero (0)
* @return last saved keyboard height in px
*/
public int getLastSoftKeyboardHeightInPx() {
return lastSoftKeyboardHeightInPx;
}
public void addSoftKeyboardStateListener(SoftKeyboardStateListener listener) {
listeners.add(listener);
}
public void removeSoftKeyboardStateListener(SoftKeyboardStateListener listener) {
listeners.remove(listener);
}
private void notifyOnSoftKeyboardOpened(int keyboardHeightInPx) {
this.lastSoftKeyboardHeightInPx = keyboardHeightInPx;
for (SoftKeyboardStateListener listener : listeners) {
if (listener != null) {
listener.onSoftKeyboardOpened(keyboardHeightInPx);
}
}
}
private void notifyOnSoftKeyboardHidden() {
for (SoftKeyboardStateListener listener : listeners) {
if (listener != null) {
listener.onSoftKeyboardHidden();
}
}
}
}
主要增加了baseDiffHeight属性,因为某些手机上的初始高度差不为0,比如华为手机的baseDiffHeight为42dp,即手机底部黑色的导航按钮栏。
结尾广告: 专业网站\app一体化解决方案提供商
http://www.h-dim.com