Android的:如何获得任意键preSS事件的例子吗?如何获得、例子、事件、Android

2023-09-13 00:36:37 作者:毛主席 我们需要你*

我想要得到的键值,当用户pressed根据pssed在机器人的关键$ P $任意键,也可以执行的操作。

i want to get the key value when user pressed any key and also perform action based on the key pressed in android.

例如。如果用户pressedA键的话,我想获得该值,比较,做一些事情。

e.g. if user pressed 'A' key then i want to get that value,compare,do something.

推荐答案

这个问题的答案应该是双重的。它是由关键是如何生成的方式来确定。如果是在硬件密钥preSS,那么下面介绍的两种方法都是有效的。如果是在软件密钥preSS,那就要看实际的上下文。

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)如果key是由长preSS上的菜单键,得到的软键盘上的pressing结果:

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和softkeyboard从它获得的,那么第一种方法不起作用,因为关键事件已经被消耗的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) 
    {
    }
);