1. There are three methods to process key events in Android gridview:
Public Boolean onkeydown (INT keycode, keyevent event)
Public Boolean onkeyup (INT keycode, keyevent event)
Public Boolean onkeylongpress (INT keycode, keyevent event)
Obviously, long-press events are handled in the onkeylongpress function.
If the time of the gridview is long, the corresponding short press event (gridview. setonitemclicklistener (), and the processing of Long-key events should not be placed in (gridview. setonlongclicklistener (), which should be put in the onkeylongpress function for processing. In this way, long-pressed and Short-pressed can be separated. If long-pressed at the beginning is followed by long-pressed, short-pressed is followed by short-pressed, the two will not be out of chaos or interference.
Take the following steps for details:
Step 1: first judge the number of event. getrepeatcount times in the onkeydown function (in fact, a long press is triggered by a series of onkeydown events)
@ Override
Public Boolean onkeydown (INT keycode, keyevent event ){
......
If (event. getrepeatcount () = 0 ){
Event. starttracking ();
Return true;
}
Return super. onkeydown (keycode, event );
}
If you keep pressing and not releasing, you can view the change in the number of event. getrepeatcount () of onkeydown through log.
Step 2: Reload the onkeylongpressed function. In this function, you can add your handling of Long-key events.
@ Override
Public Boolean onkeylongpress (INT keycode, keyevent event ){
Locklongpresskey = true;
Handling of Long-key events;
Return true;
Return super. onkeylongpress (keycode, event );
}
Step 3: If the same buttons are also processed in the onkeyup function, the processing of the buttons in onkeylongpress and onkeyup must be mutually exclusive.
Public Boolean onkeyup (INT keycode, keyevent event ){
If (locklongpresskey ){
Locklongpresskey = false;
Return true;
}
Return super. onkeyup (keycode, event );
}
The reason for mutual exclusion is that after the long-pressed event is processed, the onkeyup function is executed after the buttons are released. These two functions are different for the same button.
Add a private Boolean locklongpresskey = false here. The variable will not be processed in onkeyup after it has been processed in the onkeylongpress function.