Android:how to get any KeyPress event with example?(Android:如何通过示例获取任何 KeyPress 事件?)
问题描述
我想在用户按下任意键时获取键值,并根据在 android 中按下的键执行操作.
i want to get the key value when user pressed any key and also perform action based on the key pressed in android.
例如如果用户按下A"键,那么我想得到那个值,比较,做点什么.
e.g. if user pressed 'A' key then i want to get that value,compare,do something.
推荐答案
这个问题的答案应该是双重的.它由生成密钥的方式决定.如果它是按下硬件键,那么下面描述的两种方法都是有效的.如果是按软键,则视实际情况而定.
Answer to this question should be twofold. It is determined by the way how the key was generated. If it was press on the hardware key, then both approaches described below are valid. If it was press on the software key, then it depends on actual context.
1.) 如果按键是通过长按菜单键获得的软键盘按下的结果:
1.) If key was result of the pressing on the soft keyboard that was obtained by long press on the Menu key:
您需要小心地重写以下函数:
You need to carefully override the following function:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_A:
{
//your Action code
return true;
}
}
return super.onKeyDown(keyCode, event);
}
2.) 如果您的活动包含 EditText,并且从中获得了软键盘,则第一种方法不起作用,因为 EditText 已经使用了键事件.您需要使用文本更改的侦听器:
2.) If your activity contains EditText, and softkeyboard was obtained from it, then first approach does not work because key event was already consumed by EditText. You need to use text changed Listener:
mMyEditText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
/*This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after. It is an error to attempt to make changes to s from this callback.*/
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
);
这篇关于Android:如何通过示例获取任何 KeyPress 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android:如何通过示例获取任何 KeyPress 事件?
基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01