最近在做类似于QQ空间的功能,今天做到评论这块,功能实现思路挺简单,就是涉及的知识点比较零碎。现在做一下整理,以备日后。
1.我在Fragment里边实现的整个空间广场的功能,在点击评论按钮的时候弹出popWindow,同时需要弹出软键盘。开始想用EditText自己获取焦点系统自动调出软件盘的。结果因为使用了popWindow所以没有成功。然后改为手动调出软键盘。
弹出软件盘的代码:
/**
* 显示软键盘
*
* @param context
* @param view
*/
public static void showInputMethodForQuery(final Context context,final View view) {
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
}
}
调用时:Common.hideInputMethod(context, fragment.getView());
//这里的使用方法是错误的所以软键盘没有显示出来。
正确的应该是:Common.hideInputMethod(context, ((Activity)context).getCurrentFocus());//使用Activity的View
2、成功调出软键盘之后又出现了软键盘不能隐藏。
/**
* 隐藏软键盘
*
* @param context
* @param view
*/
public static void hideInputMethod(final Context context, final View view) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.SHOW_FORCED);
}
}
最后发现,问题出在`imm.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.SHOW_FORCED);这句代码
经过测试显示和隐藏键盘:第二个参数改成0或2就可以顺利显示和隐藏键盘(具体常量值的意思可以百度)
3.然后是软键盘的监听:
试了两种监听方法
1.
et_pl.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
//此监听只能监听到回车键
return true;
}
});
2.
et_pl.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// 此方法可以监听到删除键和回车键
return false;
}
});
但是用着两种方法都不能监听到软件盘中自带的隐藏键盘的那个向下的箭头。可惜的是软键盘的显示和隐藏并没有专门的监听事件。要想监听软键盘的显示和隐藏只能通过布局的变化来判断。我使用的方法是:
public class MyLinearLayout extends LinearLayout {
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyLinearLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// 在这里判断
super.onSizeChanged(w, h, oldw, oldh);
}
}
3、同时为了使软键盘弹出时不遮挡弹出的popWindow要给popWindow设置:
popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
4、popWindow中的EditText获取焦点必须:popupWindow.setFocusable(true);
5、让底部的菜单栏不被软件盘顶上来要在AndroidManifest.xml中设置android:windowSoftInputMode=”adjustResize”
6、本来想给软件盘的回车键修改成完成键的:通过EditText的Android:imeOptions属性设置
actionUnspecified 未指定,对应常量EditorInfo.IME_ACTION_UNSPECIFIED.
actionNone 没有动作,对应常量EditorInfo.IME_ACTION_NONE
actionGo 去往,对应常量EditorInfo.IME_ACTION_GO
actionSearch 搜索,对应常量EditorInfo.IME_ACTION_SEARCH
actionSend 发送,对应常量EditorInfo.IME_ACTION_SEND
actionNext 下一个,对应常量EditorInfo.IME_ACTION_NEXT
actionDone 完成,对应常量EditorInfo.IME_ACTION_DONE
editText.setImeOptions(EditorInfo.IME_ACTION_DONE); //代码中设置
但是要注意:要android:singleLine=”true”才可以。但是现实往往是残酷的,像搜狗输入法这种是不支持的,所以为了用户体验最后我还是在布局文件中加了个发送按钮。