这里有2种处理方法,先看复杂的:
一、软件盘弹出隐藏时在mainfest里设置 android:windowSoftInputMode="adjustResize"会改变布局的大小,即onSizeChanged()方法会被调用。
我们如果要在软件盘隐藏时操作EditText里的内容,比如软件盘隐藏时使EditText失去焦点,可用如下2种方法。
方法一:
一、自定义布局
package hyz.com;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
public class ResizeLayout extends RelativeLayout {
private OnResizeListener mListener;
public interface OnResizeListener {
void OnResize(int w, int h, int oldw, int oldh);
}
public void setOnResizeListener(OnResizeListener l)
{
Log.i("ResizeLayout:setOnResizeListener");
mListener = l;
}
public ResizeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
Log.i("ResizeLayout:ResizeLayout");
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Log.i("ResizeLayout:onSizeChanged");
if (mListener != null) {
mListener.OnResize(w, h, oldw, oldh);
}
}
}
二、引用自定义布局
<hyz.com.ResizeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/resizeLayout" android:layout_width="fill_parent" android:layout_height="fill_parent"> ...... </hyz.com.ResizeLayout>
三、在mainfest里的Activity添加
android:windowSoftInputMode="adjustResize" 如: <activity android:name=".MyTabActivity" android:screenOrientation="portrait" android:windowSoftInputMode="adjustResize">
四、在Activity中设置该布局的监听事件
首先Acitivity实现自定义布局里面的OnResizeListener接口
然后设置监听
layout = (ResizeLayout) findViewById(R.id.resizeLayout); layout.setOnResizeListener(this);
接着复写方法
@Override public void OnResize(int w, int h, int oldw, int oldh) { Log.i(h+":"+oldh); if (h >= oldh) { Log.i("CountdownActivity:OnResize()"); handler.sendEmptyMessage(MSG_CLEAR); } }
private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case MSG_CLEAR: { clearFocus(); break; } default: break; } super.handleMessage(msg); } };
上面的原理是,软件盘隐藏,导致布局大小变化,接着调用监听器,然后发送Message,最后在handler里处理事件。
方法二:这个方法在4.0以上没用,不过2.3可行,3.0的没试过
由于软件盘弹出,接着按返回键隐藏软件盘。这个返回键监听是被屏蔽了的,无法在onKeyDown()里监听返回键。
不过Acitivity里有个方法dispatchKeyEvent()
@Override public boolean dispatchKeyEvent(KeyEvent event) { Log.i("CountdownActivity:dispatchKeyEvent()"); if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) { clearFocus(); } return super.dispatchKeyEvent(event); }