最近在写评论的时候,想要以下的一个需求,就是点击评论按钮,弹出软键盘和对话框,然后按下手机返回按键之后,对话框和软键盘同时消失,而不是软件盘先消失,然后在按下back按键才能消失对话框。 先来个gif图震一下。。。哈哈(已经基本实现仿今日头条评论)(这个录屏有点延迟,真实体验和今日头条差不多,mac gif不动。。。。哎,还是在win上发布吧)

Dispatch a key event before it is processed by any input method associated with the view hierarchy. This can be used to intercept key events in special situations before the IME consumes them; a typical example would be handling the BACK key to update the application's UI instead of allowing the IME to see it and close itself.
鄙人英语也就四级水平(大家也都知道翻译水平,就类似今年的翻译老婆的翻译The people will be fuxxed(哈哈,娱乐一下)),大致意思就是,这个方法会在软键盘响应事件之前响应该方法,哈哈,听到这个时候是不是有了些许眉目了。那么是不是说在点击Back按键的时候,这个方法会优先于软键盘响应事件呢。那就测试一下吧。
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
Log.d("MyEditText", "dispatchKeyEventPreIme method is called");
return super.dispatchKeyEventPreIme(event);
}
我们点击评论按钮,这个时候弹出的对话框,我们点击back,如果走了以上的方法,那么就能实现我们的逻辑。

@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
if (mOnCancelDialogImp != null) {
mOnCancelDialogImp.onCancelDialog();
}
Log.d("MyEditText", "dispatchKeyEventPreIme method is called");
return super.dispatchKeyEventPreIme(event);
}
private OnCancelDialogImp mOnCancelDialogImp;
public void setOnCancelDialogImp(OnCancelDialogImp onCancelDialogImp) {
mOnCancelDialogImp = onCancelDialogImp;
}
/**
* 在这里定义一个接口 用于在输入框弹出的时候(评论)的时候 点击back按键不响应onKeyDown 和 onKeyPressed 方法
* 但是查询api 是可以在自定义的view里面走dispatchKeyEventPreIme这个方法的(这个方法的响应在软键盘的响应之前)
* 所以当按下back的时候,肯定会优先走这个方法 所以在这里写一个回调接口,那么就可以在调用这个回调的时候出发我们需要
* 响应的逻辑 (比如dialog隐藏)
*/
public interface OnCancelDialogImp {
void onCancelDialog();
}
###好了,接口和方法已经写好了,怎么使用呢? #####首先在xml里面把使用的官方的EditText改成我们自定义的 如下(全路径)
<com.renren.ruolan.travelaround.widget.MyEditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="随便说点什么吧"
android:textSize="14sp"
android:padding="5dp"
android:gravity="top"
android:background="@null"
/>
#####其次我们在使用的地方(也就是activity或者fragment或者其他地方)
/**
* 这个方法会在按下back键的时候出发
*/
mEditText.setOnCancelDialogImp(new MyEditText.OnCancelDialogImp() {
@Override
public void onCancelDialog() {
//判断弹框是否为空
if (mBottomDialog != null) {
mBottomDialog.dismiss(); //弹框消失
mBottomDialog = null; //赋空值
}
}
});
好了,到这个时候我们就可以实现开头那个gif的演示了。是不是听简单的。