Android - Get keyboard key press(Android - 获取键盘按键)
问题描述
我想捕捉软键盘上任意键的按下.我不想在我的 Activity 中使用 EditView 或 TextView,必须从我的 Activity 中的扩展视图处理该事件.
I want to catch the press of any key of the softkeyboard. I don't want a EditView or TextView in my Activity, the event must be handled from a extended View inside my Activity.
我刚试过这个:
1) 重写 onKeyUp(int keyCode, KeyEvent event) Activity 方法.这不适用于软键盘,它只会捕获几个硬键盘.
1) Override the onKeyUp(int keyCode, KeyEvent event)
Activity method. This don't work with softkeyboard, it just catch few hardkeyboard.
2) 创建我的 OnKeyListener
并将其注册到我的 View 中,其中包含一个已注册且正在工作的 OnTouchListener
.这对软键盘根本不起作用.
2) Create my OnKeyListener
and register that in my View that contains a registered and working OnTouchListener
. This doesn't work at all with softkeyboard.
3) 重写 onKeyUp(int keyCode, KeyEvent event)
查看方法.如果我设置我的 OnKeyListener 或不设置它,这根本不起作用.
3) Override the onKeyUp(int keyCode, KeyEvent event)
View method. This not work at all neither if I set my OnKeyListener nor if I don't set it.
4) 使用 InputMethodManager
对象调用方法 showSoftInput
并将其传递给我的视图.这对抬起键盘也不起作用,确实我必须调用 toggleSoftInput
;也没有赶上关键事件.
4) With the InputMethodManager
object Call the method showSoftInput
and passing it my View. This don't work neither for raise up the keyboard, indeed i have to call toggleSoftInput
; nor to catch the key events.
我只在模拟器中测试了所有内容,但我认为这已经足够了.为什么从键盘获取一个简单的按键事件如此复杂?
I tested all only in the emulator but i think it's enough. Why it's so complicate take a simple key event from a keyboard ?
推荐答案
要处理硬件键和返回键,您可以使用 Activity
For handling hardware keys and Back key you could use dispatchKeyEvent(KeyEvent event)
in your Activity
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
Log.i("key pressed", String.valueOf(event.getKeyCode()));
return super.dispatchKeyEvent(event);
}
UPD:很遗憾,您无法处理软键盘事件(请参阅 处理单键事件),除非您开发自己的自定义键盘(点击链接了解如何创建输入法).
UPD: unfortunately you can't handle soft keyboard events (see Handle single key events), unless you develop your own custom keyboard (follow the link to learn how Creating input method).
这篇关于Android - 获取键盘按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android - 获取键盘按键
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01