软键盘打开和关闭监听
程序员文章站
2022-04-20 08:29:20
...
1、自定义软键盘监听控件
代码如下,核心要点查看备注:
public class KeyboardLayout extends RelativeLayout {
//软键盘展开
public static final byte KEYBOARD_STATE_SHOW = -3;
//软键盘隐藏
public static final byte KEYBOARD_STATE_HIDE = -2;
//初始化软键盘
public static final byte KEYBOARD_STATE_INIT = -1;
private boolean mHasInit;
private boolean mHasKeybord;
private int mHeight;
private onKeyboaddsChangeListener mListener;
private int mScreenHeight;
public KeyboardLayout(Context context) {
super(context);
init();
}
public KeyboardLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public KeyboardLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
//屏幕尺寸信息
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
if (null != wm) {
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
mScreenHeight = outMetrics.heightPixels;
}
}
public void setOnkbdStateListener(onKeyboaddsChangeListener listener) {
mListener = listener;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (b >= mScreenHeight) {
//bottom的尺寸必须小于屏幕尺寸,一般来说都会小于,但测试发现,魅族手机会出现b==mScreenHeight,导致监听失败
return;
}
if (!mHasInit) {
mHasInit = true;
mHeight = b;
if (mListener != null) {
mListener.onKeyBoardStateChange(KEYBOARD_STATE_INIT);
}
} else {
mHeight = mHeight < b ? b : mHeight;
}
if (mHasInit && mHeight > b) {
mHasKeybord = true;
if (mListener != null) {
mListener.onKeyBoardStateChange(KEYBOARD_STATE_SHOW);
}
}
if (mHasInit && mHasKeybord && mHeight == b) {
mHasKeybord = false;
if (mListener != null) {
mListener.onKeyBoardStateChange(KEYBOARD_STATE_HIDE);
}
}
}
public interface onKeyboaddsChangeListener {
void onKeyBoardStateChange(int state);
}
}
2、进行软键盘监听
要正常使用首先需要将KeyboardLayout作为跟布局进行监听,其次KeyboardLayout.onKeyboaddsChangeListener需要实现该接口,重写:
@Override
public void onKeyBoardStateChange(int state) {
switch (state) {
case KeyboardLayout.KEYBOARD_STATE_HIDE:
//软键盘隐藏
break;
case KeyboardLayout.KEYBOARD_STATE_SHOW:
//软键盘关闭
break;
}
}
3、Eidttext光标与软键盘显示设置
如果刚刚进来需要软键盘关闭,显示光标,则需要设置:
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
4、软键盘隐藏工具类
public static void showKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) view.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
view.requestFocus();
imm.showSoftInput(view, 0);
}
}
5、软键盘显示工具类
public static void hideKeyboard(View view){
InputMethodManager imm = (InputMethodManager) view.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
}
}