Android - 获取键盘按键

时间:2023-05-05
本文介绍了Android - 获取键盘按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想捕捉软键盘上任意键的按下.我不想在我的 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 - 获取键盘按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Double 的 JFormattedTextField 仍然需要字符 下一篇:如何检查在Java中启动时按住的键

相关文章