赞
踩
假设场景图:
1.setImeOptions
用代码设置:
mEditText.setImeOptions(EditorInfo.IME_ACTION_SEND);
- <EditText
- ...
- android:imeOptions="actionSend"
- />
- mEditText.setOnKeyListener(new View.OnKeyListener() {
-
- @Override
- public boolean onKey(View v, int keyCode, KeyEvent event) {
- //这里注意要作判断处理,ActionDown、ActionUp都会回调到这里,不作处理的话就会调用两次
- if (KeyEvent.KEYCODE_ENTER == keyCode && KeyEvent.ACTION_DOWN == event.getAction()) {
- //处理事件
- return true;
- }
- return false;
- }
- });
Register a callback to be invoked when a hardware key is pressed in this view. Key presses in software input methods will generally not trigger the methods of this listener.
3.dispatchKeyEvent
也可以在Activity或者Dialog里覆写dispatchKeyEvent来达到目的:
- @Override
- public boolean dispatchKeyEvent(KeyEvent event) {
- //这里注意要作判断处理,ActionDown、ActionUp都会回调到这里,不作处理的话就会调用两次
- if (KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction()) {
- //处理事件
- return true;
- }
- return super.dispatchKeyEvent(event);
- }
4.setOnEditorActionListener
这个方法应该是最正统也最合适的,一般的做法:
- mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
-
- @Override
- public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
- if (actionId == EditorInfo.IME_ACTION_SEND) {
- //处理事件
- }
- return false;
- }
- });
- mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
-
- @Override
- public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
- //当actionId == XX_SEND 或者 XX_DONE时都触发
- //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
- //注意,这是一定要判断event != null。因为在某些输入法上会返回null。
- if (actionId == EditorInfo.IME_ACTION_SEND
- || actionId == EditorInfo.IME_ACTION_DONE
- || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
- //处理事件
- }
- return false;
- }
- });
文档说明:
总结:软键盘回车键事件只需要用方法4就可以轻松解决,也是最合适的方法。
希望对大家有所帮助,谢谢!
http://blog.csdn.net/Iceshow0428/article/details/24428417
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。