软件盘的监听。android并没有直接提供给我们方法。我们只有间接的去判断软键盘是否弹出了。
首先要在清单文件中给activity设置 软件盘的弹出模式为:
android:windowSoftInputMode="adjustResize" 在此种模式下才能监测到软件盘弹出。此种模式为布局在软件盘弹出后为软键盘自动腾出位置。相对于"adjustPan"此种模式下布局不会为软键盘腾位置。如果我们在清单文件中不设置的话。系统默认模式为"stateUnspecified".此时系统会自己选择一个合适的状态。要监测到软件盘必须选择在"adjustResize"模式下.但是此种模式下会有布局被软件盘推的问题。会导致布局错位。我验证过。只有相对布局才会被推的错位。所以要监测到软键盘是否弹出。该activity下的根布局一定是线性布局。就不会出现该问题。现在直接上代码。
方法一:依靠view的addOnLayoutChangeListener的监听。判读根布局大小是否改变。
private int screenHeight = 0;//屏幕高度 private int keyHeight = 0;//软件盘弹起后所占高度阀值 private boolean isPopup=false;//默认软件盘 没弹出
rootview.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高,就认为软键盘弹起 if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) { isPopup = true;//软键盘弹起 } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) { isPopup = false; } } });
方法二:第二种方法比第一种方法略麻烦。但是听别人说监听的更准确。具体效果未知
首先自定义一个布局。可以监测到布局的变化。这个自定义的布局,替换我们的activity的根布局。原理和上一个一样
public class ResizeLayout extends LinearLayout { public ResizeLayout(Context context, AttributeSet attrs) { super(context, attrs); } private OnResizeListener mListener; public interface OnResizeListener { void OnResize(int w, int h, int oldw, int oldh); } public void setOnResizeListener(OnResizeListener l) { mListener = l; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (mListener != null) { mListener.OnResize(w, h, oldw, oldh); } } }在activity代码里加入。
private static final int BIGGER = 1; private static final int SMALLER = 2; private static final int MSG_RESIZE = 1; private boolean isKeyBordup=false;//默认软件盘 没弹出
class InputHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_RESIZE: { if (msg.arg1 == BIGGER) { isKeyBordup=false; } else {//键盘弹起 isKeyBordup=true; } } break; default: break; } super.handleMessage(msg); } } private InputHandler mHandler = new InputHandler();
private void softWindowChange() { ResizeLayout layout = (ResizeLayout) findViewById(R.id.ll_cattle_turnup_ay); layout.setOnResizeListener(new ResizeLayout.OnResizeListener() { public void OnResize(int w, int h, int oldw, int oldh) { int change = BIGGER; if (h < oldh) { change = SMALLER; } Message msg = new Message(); msg.what = 1; msg.arg1 = change; mHandler.sendMessage(msg); } }); }