默认进入页面便开始获取软键盘高度。实现无需手动打开软键盘即可获取软键盘高度。
public class HeightProvider extends PopupWindow implements ViewTreeObserver.OnGlobalLayoutListener { private Activity mActivity; private View rootView; private HeightListener listener; private int heightMax; public HeightProvider(Activity activity) { super(activity); this.mActivity = activity; rootView = new View(activity); setContentView(rootView); rootView.getViewTreeObserver().addOnGlobalLayoutListener(this); setBackgroundDrawable(new ColorDrawable(0)); setWidth(0); setHeight(WindowManager.LayoutParams.MATCH_PARENT); setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); } public HeightProvider init() { if (!isShowing()) { final View view = mActivity.getWindow().getDecorView(); view.post(new Runnable() { @Override public void run() { showAtLocation(view, Gravity.NO_GRAVITY, 0, 0); } }); } return this; } public HeightProvider setHeightListener(HeightListener listener) { this.listener = listener; return this; } @Override public void onGlobalLayout() { Rect rect = new Rect(); rootView.getWindowVisibleDisplayFrame(rect); if (rect.bottom > heightMax) { heightMax = rect.bottom; } int keyboardHeight = heightMax - rect.bottom; if (listener != null) { listener.onHeightChanged(keyboardHeight); } } public interface HeightListener { void onHeightChanged(int height); } }使用
new HeightProvider(this).init().setHeightListener(new HeightProvider.HeightListener() { final float scale = mContext.getResources().getDisplayMetrics().density; @Override public void onHeightChanged(int height) { if (height > 0) { //height为软件盘高度 } else { //height为软件盘高度 } } });