• 4
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

What is the difference between onKey(), OnKeyDown() and dispatchKeyEvent() methods provided by Android?
I Would like to know when and where each of these can be used.
Please shed some light into this.

Tracing the source code of the 5.1 Source for the View Class. It would seem that dispatchKeyEvent() is the first method called by the system. Overloading it will prevent any and all key events from being called unless the base version is called.

dispatchKeyEvent()'s first move is to attempt to pass the event to an onKeyListener if there is one. This is when onKey() is called. If the onKey() implementation returns true, dispatchKeyEvent() will return there and other events will not be called.

If there is no onKeyListener or the onKeyListener's onKey() method returned false, dispatchKeyEvent() will then call the KeyEvent's dispatch() method. Which will then in turn call all the methods in the KeyEvent.Callback interface on your view. This includes onKeyDown() and onKeyUp().

  • 55
Reply Report
      • 1
    • So, instead of using both onKeyDown and onKeyUp, I could also just use dispatchKeyEvent? Does this have any drawbacks? I had to do this, because onKeyDown wouldn't be triggered for most of the keys, for some reason. When I changed to dispatchKeyEvent, it worked.
      • 2
    • @keinabel Overloading dispatchKeyEvent is an option. But unless you call the base version no other related events will be fired. In your situation my guess would be that your events are being consumed by an onKeyListener before KeyEvent.dispatch() is called, or that the key presses are being seen as an onKeyMultiple event by the dispatch() method.

DispatchKeyEvent Hardware key events are always delivered to the View currently in focus. They are dispatched starting from the top of the View hierarchy, and then down, until they reach the appropriate destination. If your View (or a child of your View) currently has focus, then you can see the event travel through the dispatchKeyEvent() method. In short, dispatchKeyEvent() will be only called if TextView/EditText is in focus.

onKeyDown Called when a key was pressed down and not handled by any of the views inside of the activity

  • 0
Reply Report