Step 5. ViewRoot.deliverKeyEventToViewHierarchy

  [java] view plaincopyprint?

  public final class ViewRoot extends Handler implements ViewParent,

  View.AttachInfo.Callbacks {

  ......

  private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {

  try {

  if (mView != null && mAdded) {

  final int action = event.getAction();

  boolean isDown = (action == KeyEvent.ACTION_DOWN);

  ......

  boolean keyHandled = mView.dispatchKeyEvent(event);

  if (!keyHandled && isDown) {

  int direction = 0;

  switch (event.getKeyCode()) {

  case KeyEvent.KEYCODE_DPAD_LEFT:

  direction = View.FOCUS_LEFT;

  break;

  case KeyEvent.KEYCODE_DPAD_RIGHT:

  direction = View.FOCUS_RIGHT;

  break;

  case KeyEvent.KEYCODE_DPAD_UP:

  direction = View.FOCUS_UP;

  break;

  case KeyEvent.KEYCODE_DPAD_DOWN:

  direction = View.FOCUS_DOWN;

  break;

  }

  if (direction != 0) {

  View focused = mView != null ? mView.findFocus() : null;

  if (focused != null) {

  View v = focused.focusSearch(direction);

  ......

  if (v != null && v != focused) {

  ......

  focusPassed = v.requestFocus(direction, mTempRect);

  }

  ......

  }

  }

  }

  }

  } finally {

  if (sendDone) {

  finishInputEvent();

  }

  ......

  }

  }

  ......

  }

  public final class ViewRoot extends Handler implements ViewParent,

  View.AttachInfo.Callbacks {

  ......

  private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {

  try {

  if (mView != null && mAdded) {

  final int action = event.getAction();

  boolean isDown = (action == KeyEvent.ACTION_DOWN);

  ......

  boolean keyHandled = mView.dispatchKeyEvent(event);

  if (!keyHandled && isDown) {

  int direction = 0;

  switch (event.getKeyCode()) {

  case KeyEvent.KEYCODE_DPAD_LEFT:

  direction = View.FOCUS_LEFT;

  break;

  case KeyEvent.KEYCODE_DPAD_RIGHT:

  direction = View.FOCUS_RIGHT;

  break;

  case KeyEvent.KEYCODE_DPAD_UP:

  direction = View.FOCUS_UP;

  break;

  case KeyEvent.KEYCODE_DPAD_DOWN:

  direction = View.FOCUS_DOWN;

  break;

  }

  if (direction != 0) {

  View focused = mView != null ? mView.findFocus() : null;

  if (focused != null) {

  View v = focused.focusSearch(direction);

  ......

  if (v != null && v != focused) {

  ......

  focusPassed = v.requestFocus(direction, mTempRect);

  }

  ......

  }

  }

  }

  }

  } finally {

  if (sendDone) {

  finishInputEvent();

  }

  ......

  }

  }

  ......

  }

  这个函数定义在文件frameworks/base/core/java/android/view/ViewRoot.java中。