Android 输入回车键发送消息,并且收起软键盘


点击输入框输入内容时,输入完成的时候,想通过直接点击软键盘中的回车键直接收起软键盘,并且发送内容或者搜索内容。

1.首先在xml中设置一个地方,加一个属性

 

<EditText
     android:id="@+id/et_title"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:imeOptions="actionSearch"
     android:singleLine="true" />
 

默认情况下软键盘右下角的按钮为“下一个”,点击会到下一个输入框,设置imeOptions的值为actionSearch、actionDone、actionSend等,软键盘下方变成“搜索”、“完成”、“发送”等。(注:有可能"搜索"不是以文字形式展现的,也许会以一个图标展现,也就是一个放大镜图标,所以如果你的是这样,别疑惑)

上面只是举几个例子,还有的值读者可以自己去探索试试。

2.接下来就是监听键盘的回车键了:

EditText实现setOnEditorActionListener,在onEditAction方法中actionId就对应我们设置的imeOptions。系统默认的actionId有:EditorInfo.IME_NULL、EditorInfo.IME_ACTION_SEND、EditorInfo.IME_ACTION_DONE等。

findViewById(R.id.et_title).setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { //搜索(发送消息)操作(此处省略,根据读者自己需要,直接调用自己想实现的方法即可)
 
//收起软键盘 InputMethodManager im = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } return false; } });

在输入回车的时候也要收起软键盘,此时就稍微开展记录点软键盘的显示和隐藏吧

 InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

// 获取软键盘的显示状态
boolean isOpen = imm.isActive();

// 如果软键盘已经显示,则隐藏,反之则显示
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

// 隐藏软键盘
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

// 强制显示软键盘
imm.showSoftInput(getActivity().getCurrentFocus(), InputMethodManager.SHOW_FORCED);

// 强制隐藏软键盘
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);

 

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM