Androidソフトキーボードの傍受(傍受高さ、表示するかどうか)

1182 ワード

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;
				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);
	}
}