如何访问菜单按钮onLongClick在Android中?按钮、菜单、Android、onLongClick

2023-09-07 15:57:28 作者:情敌别怂。

我如何设置一个侦听器长按硬件菜单按钮执行?什么是编程访问菜单按钮?

How can I set a listener for long-click performed on hardware Menu button? What is the way of programmatic access to the Menu button?

另外我怎么能区分长单击单单击? (据我知道什么时候长按进行单点击事件传播,以及 - 我不希望这种情况发生,因为我需要这2个的情况下2个不同的动作长按和单点击单独的侦听器设备菜单按钮)

Moreover how can I distinguish long-click from single-click? (As far as I know when long-click is performed the single-click event is propagated as well - I do not want this to happen because I need 2 different actions for these 2 situations. Long-click and single-click separate listeners for the device Menu button)

感谢您!

推荐答案

这shoule是相当简单的。看看在Android开发者网站上的 KeyEvent.Callback 。

This shoule be fairly straight forward. Check out the KeyEvent.Callback on the Android developer's website.

在那里,你会发现 onKeyLong preSS()以及的onkeydown()的onkeyup()。这应该让你在正确的轨道。注释如果您需要任何进一步的帮助后您code。

There you will find onKeyLongPress() as well as onKeyDown() and onKeyUp(). This should get you on the right track. Comment or post you code if you need any further help.

编辑:我只是重新阅读问题。如果您无法区分单一的点击来自长按,你需要使用的onkeydown 的onkeyup 和检查时间的点击。 Esentially你将开始在的onkeydown 计时器和检查的时间在的onkeyup 。你必须要留意 FLAG_CANCELED

I just re-read the question. If you are having trouble distinguishing single click from long click, you will need to use onKeyDown and onKeyUp and check the duration of the click. Esentially you will start a timer in the onKeyDown and check the time in the onKeyUp. You will have to watch for FLAG_CANCELED.

另外编辑:我发现的时候做了几个测试。这code应该做你想做的(的onkeyup()仅仅得到短暂preSS事件和 onLong preSS()只获得长期preSS事件)。

Further I found the time to do a couple of tests. This code should do what you want (onKeyUp() gets only short press events and onLongPress() gets only long press events).

这里的关键是在调用 event.startTracking()的onkeydown()处理程序。

The key thing here is in the call to event.startTracking() in the onKeyDown() handler.

放在活动(这应该也是一个自定义视图的工作很好,但未经测试):

Place in Activity (this should also work in a custom view as well but untested):

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        // Handle Long Press here
        Log.i("KeyCheck", "LongPress");
        return true;    
    }
    return super.onKeyLongPress(keyCode, event);
}
@Override   
public boolean onKeyDown(int keyCode, KeyEvent event) {
    Log.i("KeyCheck", "KeyDown" + keyCode);
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        event.startTracking(); //call startTracking() to get LongPress event
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU && event.isTracking()
            && !event.isCanceled()) {
        // handle regular key press here
        Log.i("KeyCheck", "KeyUp");
        return true;
    }
    return super.onKeyUp(keyCode, event);
}