問題描述
我想在用戶按下任意鍵時獲取鍵值,并根據在 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 事件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!