Android键盘工具类

tech2022-12-20  112

import android.app.Activity; import android.content.Context; import android.graphics.Rect; import android.view.View; import android.view.ViewTreeObserver; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; public class KeyBoardUtils { int screenHeight6; View rootView; Activity mContext; int virtualKeyboardHeight;//虚拟键盘高度 int screenHeight;//屏幕高度 /** * 打开/关闭软键盘 * @param mEditText 输入框 * @param mContext 上下文 * 其他切换方法:activity的adjustPan/adjustResize * 其他切换方法:<request/> requestFocus clearFocus */ public static void toggleKeybord(EditText mEditText, Context mContext) { InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS); } /** * 打开软键盘 * @param mEditText 输入框 * @param mContext 上下文 */ public static void openKeybord(EditText mEditText, Context mContext) { InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(mEditText, InputMethodManager.SHOW_FORCED); } /** * 关闭软键盘 * @param mEditText 输入框 * @param mContext 上下文 */ public static void closeKeybord(EditText mEditText, Context mContext) { InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); } public KeyBoardUtils(Activity context) { this.mContext = context; /** * 获取屏幕的高度,该方式的获取不包含虚拟键盘 */ screenHeight = mContext.getResources().getDisplayMetrics().heightPixels; screenHeight6 = screenHeight / 6; rootView = mContext.getWindow().getDecorView(); } /** * 监听键盘是否弹出 * @param listener */ public void setOnKeyboardChangeListener(final KeyboardChangeListener listener) { rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { //当键盘弹出隐藏的时候会 调用此方法。 @Override public void onGlobalLayout() { /** * 回调该方法时rootView还未绘制,需要设置绘制完成监听 */ rootView.post(new Runnable() { @Override public void run() { Rect rect = new Rect(); /** * 获取屏幕底部坐标 */ rootView.getWindowVisibleDisplayFrame(rect); /** * 获取键盘的高度 */ int heightDifference = screenHeight - rect.bottom; if (heightDifference < screenHeight6) { virtualKeyboardHeight = heightDifference; if (listener != null) { listener.onKeyboardHide(); } } else { if (listener != null) { listener.onKeyboardShow(heightDifference - virtualKeyboardHeight); } } } }); } }); } /** * 软键盘状态切换监听 */ public interface KeyboardChangeListener { /** * 键盘弹出 * * @param keyboardHight 键盘高度 */ void onKeyboardShow(int keyboardHight); /** * 键盘隐藏 */ void onKeyboardHide(); } }
最新回复(0)