Android官方本身没有提供一共好的方法来对软键盘进行监听,但我们实际应用时。非常多地方都须要针对软键盘来对UI进行一些优化。

下面是整理出来的一个不错的方法。大家能够使用。

public class SoftKeyboardUtil {
	public static void observeSoftKeyboard(Activity activity, final OnSoftKeyboardChangeListener listener) {
		final View decorView = activity.getWindow().getDecorView();
		decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            int previousKeyboardHeight = -1;
			@Override
			public void onGlobalLayout() {
				Rect rect = new Rect();
				decorView.getWindowVisibleDisplayFrame(rect);
				int displayHeight = rect.bottom - rect.top;
				int height = decorView.getHeight();
                int keyboardHeight = height - displayHeight;
                if (previousKeyboardHeight != keyboardHeight) {
                    boolean hide = (double) displayHeight / height > 0.8;
                    listener.onSoftKeyBoardChange(keyboardHeight, !hide);
                }

                previousKeyboardHeight = height;

			}
		});
	}

	public interface OnSoftKeyboardChangeListener {
		void onSoftKeyBoardChange(int softKeybardHeight, boolean visible);
	}
}




相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-01
  • 2022-12-23
  • 2021-07-18
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案