Created
August 18, 2017 03:33
-
-
Save 410063005/8d128976c13409ee870b4bdaed434c79 to your computer and use it in GitHub Desktop.
Android监听软键盘
This file contains 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://stackoverflow.com/questions/25216749/softkeyboard-open-and-close-listener-in-an-activity-in-android | |
public class SoftKeyboardMonitor { | |
private final BaseActivity mActivity; | |
private KeyboardListener mKeyboardListener; | |
private View rootLayout; | |
private boolean isOpened; | |
public SoftKeyboardMonitor(BaseActivity activity) { | |
mActivity = activity; | |
if (activity instanceof KeyboardListener) { | |
mKeyboardListener = (KeyboardListener) activity; | |
} | |
} | |
public void attach(View view) { | |
detach(); | |
rootLayout = view; | |
rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener); | |
} | |
public void detach() { | |
if (rootLayout != null) { | |
removeGlobalOnLayoutListenerCompact(rootLayout.getViewTreeObserver(), keyboardLayoutListener); | |
rootLayout = null; | |
} | |
} | |
private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { | |
@Override | |
public void onGlobalLayout() { | |
if (mActivity.isActivityDestroyed()) { | |
return; | |
} | |
int heightDiff = rootLayout.getRootView().getHeight() - rootLayout.getHeight(); | |
int contentViewTop = mActivity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); | |
if (rootLayout.getHeight() > 2 * SystemUtils.getScreenHeight(mActivity) / 3) { | |
if (mKeyboardListener != null) mKeyboardListener.onHideKeyboard(); | |
isOpened = false; | |
} else { | |
Log.i("SoftKeyboardMonitor", "onGlobalLayout: "); | |
int keyboardHeight = heightDiff - contentViewTop; | |
if (!isOpened) { | |
if (mKeyboardListener != null) mKeyboardListener.onShowKeyboard(keyboardHeight); | |
} | |
isOpened = true; | |
} | |
} | |
}; | |
private void removeGlobalOnLayoutListenerCompact(ViewTreeObserver observer, ViewTreeObserver.OnGlobalLayoutListener listener) { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { | |
observer.removeOnGlobalLayoutListener(listener); | |
} else { | |
observer.removeGlobalOnLayoutListener(listener); | |
} | |
} | |
public interface KeyboardListener { | |
void onHideKeyboard(); | |
void onShowKeyboard(int height); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment