Android没有对软键盘设置监听事件,这需要我们去收到去设置软键盘显示和隐藏做监听
1.实现原理
软件盘抬起会改变到屏幕底部的距离,根据这个原理我们在onLayout中就能判断出键盘时候抬起。
2.实现步骤
1)在AndroidManifast.xml中设置activity android:windowSoftInputMode="stateAlwaysHidden|adjustResize"
2)自定义一个view重写onLayout方法
3.代码实现
AndroidManifast.xml
<activity
android:name="com.keyboarddemo.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustResize"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
KeyboardLayout
public class KeyboardLayout extends LinearLayout {
public KeyboardLayout(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public KeyboardLayout(Context context)
{
super(context);
}
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 OnKeyboardsChangeListener mListener;
private int state=KEYBOARD_STATE_INIT;
public void setOnkeyboardStateListener(OnKeyboardsChangeListener 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 (!mHasInit) {
mHasInit = true;
mHeight = b;
if (mListener != null) {
mListener.onKeyBoardStateChange(KEYBOARD_STATE_INIT);
}
} else {
mHeight = mHeight < b ? b : mHeight;
}
if (mHasInit && mHeight > b + 200 && state != KEYBOARD_STATE_SHOW) {
mHasKeybord = true;
if (mListener != null) {
mListener.onKeyBoardStateChange(KEYBOARD_STATE_SHOW);
}
state = KEYBOARD_STATE_SHOW;
}
if (mHasInit && mHasKeybord && mHeight <= b+200 && state != KEYBOARD_STATE_HIDE) {//加200是为了防止有些手机又虚拟返回键
mHasKeybord = false;
if (mListener != null) {
mListener.onKeyBoardStateChange(KEYBOARD_STATE_HIDE);
}
state = KEYBOARD_STATE_HIDE;
}
}
public interface OnKeyboardsChangeListener{
public void onKeyBoardStateChange(int state);
}
}
4.附加信息
android:windowSoftInputMode各值得含意
【A】stateUnspecified:软键盘的状态并没有指定,系统将选择一个合适的状态或依赖于主题的设置
【B】stateUnchanged:当这个activity出现时,软键盘将一直保持在上一个activity里的状态,无论是隐藏还是显示
【C】stateHidden:用户选择activity时,软键盘总是被隐藏
【D】stateAlwaysHidden:当该Activity主窗口获取焦点时,软键盘也总是被隐藏的
【E】stateVisible:软键盘通常是可见的
【F】stateAlwaysVisible:用户选择activity时,软键盘总是显示的状态
【G】adjustUnspecified:默认设置,通常由系统自行决定是隐藏还是显示
【H】adjustResize:该Activity总是调整屏幕的大小以便留出软键盘的空间
【I】adjustPan:当前窗口的内容将自动移动以便当前焦点从不被键盘覆盖和用户能总是看到输入内容的部分