焦点分发、拦截过程
Android中KeyEvent事件很多,位于android.view下,KeyEvent主要有以下事件类型:
KeyEvent.KEYCODE_DPAD_UP; 上
KeyEvent.KEYCODE_DPAD_DOWN; 下
KeyEvent.KEYCODE_DPAD_LEFT;左
KeyEvent.KEYCODE_DPAD_RIGHT;右
KeyEvent.KEYCODE_DPAD_CENTER;确定键
KeyEvent.KEYCODE_DPAD_RIGHT; 右
KeyEvent.KEYCODE_XXX:数字键 (xx表示你按了数字几)
KeyEvent.KEYCODE_BACK; 返回键
KeyEvent.KEYCODE_HOME;房子键
KeyEvent.KEYCODE_A: A-Z,26个字母
KeyEvent.KEYCODE_MENU菜单键。
ViewRootImpl中的类部类
ViewPostImeInputStage.processKeyEvent(QueuedInputEvent q)
--->DecorView.dispatchKeyEvent(event)
--->Activity.dispatchKeyEvent(event)
Android焦点事件的分发是从ViewRootImpl的ViewPostImeInputStage.processKeyEvent(QueuedInputEvent q) 开始的,源码如下:
private int processKeyEvent(QueuedInputEvent q) {
final KeyEvent event = (KeyEvent)q.mEvent;
if (mUnhandledKeyManager.preViewDispatch(event)) {
return FINISH_HANDLED;
}
// Deliver the key to the view hierarchy.
if (mView.dispatchKeyEvent(event)) {
return FINISH_HANDLED;
}
if (shouldDropInputEvent(q)) {
return FINISH_NOT_HANDLED;
}
// This dispatch is for windows that don't have a Window.Callback. Otherwise,
// the Window.Callback usually will have already called this (see
// DecorView.superDispatchKeyEvent) leaving this call a no-op.
if (mUnhandledKeyManager.dispatch(mView, event)) {
return FINISH_HANDLED;
}
int groupNavigationDirection = 0;
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_TAB) {
if (KeyEvent.metaStateHasModifiers(event.getMetaState(), KeyEvent.META_META_ON)) {
groupNavigationDirection = View.FOCUS_FORWARD;
} else if (KeyEvent.metaStateHasModifiers(event.getMetaState(),
KeyEvent.META_META_ON | KeyEvent.META_SHIFT_ON)) {
groupNavigationDirection = View.FOCUS_BACKWARD;
}
}
// If a modifier is held, try to interpret the key as a shortcut.
// 分发按键事件到视图树,mView即是DecorView
if (event.getAction() == KeyEvent.ACTION_DOWN
&& !KeyEvent.metaStateHasNoModifiers(event.getMetaState())
&& event.getRepeatCount() == 0
&& !KeyEvent.isModifierKey(event.getKeyCode())
&& groupNavigationDirection == 0) {
if (mView.dispatchKeyShortcutEvent(event)) {
return FINISH_HANDLED;
}
if (shouldDropInputEvent(q)) {
return FINISH_NOT_HANDLED;
}
}
// Apply the fallback event policy.
if (mFallbackEventHandler.dispatchKeyEvent(event)) {
return FINISH_HANDLED;
}
if (shouldDropInputEvent(q)) {
return FINISH_NOT_HANDLED;
}
// Handle automatic focus changes.
// 如果是按键按下事件,则处理焦点自动导航
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (groupNavigationDirection != 0) {
if (performKeyboardGroupNavigation(groupNavigationDirection)) {
return FINISH_HANDLED;
}
} else {
if (performFocusNavigation(event)) { // direction值是后面来进行焦点查找的
return FINISH_HANDLED;
}
}
}
return FORWARD;
}
- 首先由dispatchKeyEvent进行焦点的分发,如果dispatchKeyEvent方法返回true(代表事件已消费),那么下面的焦点查找将被终止
if (mView.dispatchKeyEvent(event)) {
return FINISH_HANDLED;
}
首先会执行mView的dispatchKeyEvent方法,这个mView是Activity的顶层容器DecorView,是一个FrameLayout。所以这里的dispatchKeyEvent方法应该执行的是ViewGroup的dispatchKeyEvent()方法,而不是View的dispatchKeyEvent方法。其中:
DecorView的dispatchKeyEvent方法源码:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
final int keyCode = event.getKeyCode();
final int action = event.getAction();
final boolean isDown = action == KeyEvent.ACTION_DOWN;
if (isDown && (event.getRepeatCount() == 0)) {
// First handle chording of panel key: if a panel key is held
// but not released, try to execute a shortcut in it.
if ((mWindow.mPanelChordingKey > 0) && (mWindow.mPanelChordingKey != keyCode)) {
boolean handled = dispatchKeyShortcutEvent(event);
if (handled) {
return true;
}
}
// If a panel is open, perform a shortcut on it without the
// chorded panel key
if ((mWindow.mPreparedPanel != null) && mWindow.mPreparedPanel.isOpen) {
if (mWindow.performPanelShortcut(mWindow.mPreparedPanel, keyCode, event, 0)) {
return true;
}
}
}
if (!mWindow.isDestroyed()) {
//DecorView中的mWindow唯一实现类就是PhoneWindow,而Activity则是Window.Callback是实现类。Activity中调用mWindow.setCallback(this)
//故而,此处mWindow.getCallback()获取到的就是Activity实例,调用cb.dispatchKeyEvent(event)实际上就是调用到Activity.dispatchKeyEvent(event)
//Activity会在其dispatchKeyEvent(event)方法中做一些按键事件分发处理。如onKeyDown、onKeyUp、onKeyLongPress、onKeyMultiple方法的回调
//这些回调方法中,如果消费了事件,则返回true,结束事件继续分发;如果不消费事件,则返回false,继续调用父类super.dispatchKeyEvent(event)方法层层递归进行事件分发
final Window.Callback cb = mWindow.getCallback();
final boolean handled = cb != null && mFeatureId < 0 ? cb.dispatchKeyEvent(event)
: super.dispatchKeyEvent(event);
if (handled) {
return true;
}
}
return isDown ? mWindow.onKeyDown(mFeatureId, event.getKeyCode(), event)
: mWindow.onKeyUp(mFeatureId, event.getKeyCode(), event);
}
Activity的dispatchKeyEvent方法源码:
/**
* Called to process key events. You can override this to intercept all
* key events before they are dispatched to the window. Be sure to call
* this implementation for key events that should be handled normally.
*
* @param event The key event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchKeyEvent(KeyEvent event) {
onUserInteraction();
// Let action bars open menus in response to the menu key prioritized over
// the window handling it
final int keyCode = event.getKeyCode();
if (keyCode == KeyEvent.KEYCODE_MENU &&
mActionBar != null && mActionBar.onMenuKeyEvent(event)) {
return true;
}
Window win = getWindow();
if (win.superDispatchKeyEvent(event)) {
return true;
}
View decor = mDecor;
if (decor == null) decor = win.getDecorView();
//调用KeyEvent event对象的dispatch(Callback receiver, DispatcherState state,Object target)方法
//把事件接收的处理者作为reciver传入,进行事件的处理。例如,调用事件接收者的onKeyDown、onKeyUp、onKeyLongPress、onKeyMultiple方法的回调
//事件处理的结果会向上层回传给DecorView.dispatchKeyEvent()-->mView.dispatchKeyEvent(event)
// 如果返回true,则消费事件,直接将结果回传到ViewRootImpl中的mView.dispatchKeyEvent(event);
// 如果返回false,则DecorView会调用super.dispatchKeyEvent(event)层层递归分发事件直到返回结果。
//
return event.dispatch(this, decor != null
? decor.getKeyDispatcherState() : null, this);
}
ViewGroup的dispatchKeyEvent()方法的源码如下:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onKeyEvent(event, 1);
}
if ((mPrivateFlags & (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS))
== (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS)) {
if (super.dispatchKeyEvent(event)) {
return true;
}
} else if (mFocused != null && (mFocused.mPrivateFlags & PFLAG_HAS_BOUNDS)
== PFLAG_HAS_BOUNDS) {
if (mFocused.dispatchKeyEvent(event)) {
return true;
}
}
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 1);
}
return false;
}
ViewGroup的dispatchKeyEvent执行过程
-
首先ViewGroup会一层一层往上执行父类的dispatchKeyEvent方法,如果返回true那么父类的dispatchKeyEvent方法就会返回true,也就代表父类消费了该焦点事件,那么焦点事件自然就不会往下进行分发。
-
然后ViewGroup会判断mFocused这个view是否为空,如果为空就会return false,焦点继续往下传递;如果不为空,那就会return mFocused的dispatchKeyEvent方法返回的结果。这个mFocused是什么呢?其实是ViewGroup中当前获取焦点的子View,这个可以从requestChildFocus方法中得到答案。requestChildFocus()的源码如下:
@Override
public void requestChildFocus(View child, View focused) {
if (DBG) {
System.out.println(this + " requestChildFocus()");
}
if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) {
return;
}
// Unfocus us, if necessary
super.unFocus(focused);
// We had a previous notion of who had focus. Clear it.
if (mFocused != child) {
if (mFocused != null) {
mFocused.unFocus(focused);
}
mFocused = child;
}
if (mParent != null) {
mParent.requestChildFocus(this, focused);
}
}
View的dispatchKeyEvent方法的执行过程
public boolean dispatchKeyEvent(KeyEvent event) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onKeyEvent(event, 0);
}
// Give any attached key listener a first crack at the event.
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
return true;
}
if (event.dispatch(this, mAttachInfo != null
? mAttachInfo.mKeyDispatchState : null, this)) {
return true;
}
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
return false;
}
我们发现这里调用了onKeyListener中的onKey方法,如果onKey方法返回true,那么dispatchKeyEvent方法也会返回true。所以如果我们想要修改ViewGroup焦点事件的分发,可以重写view的dispatchKeyEvent方法;或者给某个子view设置onKeyListener监听。但在实际开发中,所有焦点问题都可以通过给dispatchKeyEvent方法来拦截来控制。
我们通过ViewRootImpl中可以看到,如果dispatchKeyEvent方法返回false后,先得到按键的方向direction值,这个值是一个int类型参数。这个direction值是后面来进行焦点查找的。
private boolean performFocusNavigation(KeyEvent event) {
int direction = 0;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.hasNoModifiers()) {
direction = View.FOCUS_LEFT;
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.hasNoModifiers()) {
direction = View.FOCUS_RIGHT;
}
break;
case KeyEvent.KEYCODE_DPAD_UP:
if (event.hasNoModifiers()) {
direction = View.FOCUS_UP;
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (event.hasNoModifiers()) {
direction = View.FOCUS_DOWN;
}
break;
case KeyEvent.KEYCODE_TAB:
if (event.hasNoModifiers()) {
direction = View.FOCUS_FORWARD;
} else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
direction = View.FOCUS_BACKWARD;
}
break;
}
// _______________________________根据按键方向查找焦点________________________________
if (direction != 0) {
//mView:即DecorView,DecorView是整个ViewTree的最顶层View,它是一个FrameLayout布局,代表了整个应用的界面.
View focused = mView.findFocus();//从视图树的顶层,即DecorView一层一层的递归查找当前获得焦点的view
if (focused != null) {
//找到了当前获得焦点的focused,调用该焦点view的focusSearch(direction)方法查找direction方向上下一个将要获取焦点的view
//focused.focusSearch(direction)实际上会调用mParent.focusSearch(this, direction)方法,层层递归,直到调用到DecorView的focusSearch(this, direction)方法。
//而DecorView继承ViewGroup,实际上最终会调用到FocusFinder.getInstance().findNextFocus(this, focused, direction),this 就是DecorView对象
View v = focused.focusSearch(direction);
if (v != null && v != focused) {//找到下一个可获取焦点view,并且不是当前获取焦点的view
// do the math the get the interesting rect
// of previous focused into the coord system of
// newly focused view
focused.getFocusedRect(mTempRect);
if (mView instanceof ViewGroup) {
((ViewGroup) mView).offsetDescendantRectToMyCoords(
focused, mTempRect);
((ViewGroup) mView).offsetRectIntoDescendantCoords(
v, mTempRect);
}
//让找到的下一个可获取焦点的view获取焦点
//该v可能是view或者是ViewGroup。 ViewGroup获取焦点的最大区别就是重写了View.requestFocus(int direction, Rect previouslyFocusedRect)方法。
//ViewGroup会根据指定的焦点策略(FOCUS_BEFORE_DESCENDANTS、FOCUS_AFTER_DESCENDANTS、FOCUS_BLOCK_DESCENDANTS)来处理焦点在自己和子View之间的流转。
if (v.requestFocus(direction, mTempRect)) {//获取到焦点后,该焦点view会层层上报自己的parent,让parent做出相应的响应
//播放声音
playSoundEffect(SoundEffectConstants
.getContantForFocusDirection(direction));
//新的view已经获取到了焦点,返回true消费事件,事件不再往下继续执行。
return true;
}
}
// Give the focused view a last chance to handle the dpad key.
//给当前获取焦点的focused view 最后一次处理事件的机会
//即,focused.focusSearch(direction)查找的下个可获取焦点的view 为null时 获取前面的事件未被消费调,会获得执行机会
if (mView.dispatchUnhandledMove(focused, direction)) {
//从DecorView开始,递归调用dispatchUnhandledMove(focused, direction),直到focused中的dispatchUnhandledMove(focused, direction)
return true;
}
} else {
//递归调用,重置默认焦点(整个视图树上只能有唯一一个默认焦点view)
if (mView.restoreDefaultFocus()) {
return true;
}
}
}
return false;
}
接着会调用DecorView的findFocus()方法一层一层往下查找已经获取焦点的子View。 ViewGroup的findFocus方法如下:
@Override
public View findFocus() {
if (DBG) {
System.out.println("Find focus in " + this + ": flags="
+ isFocused() + ", child=" + mFocused);
}
if (isFocused()) {
return this; // 返回自身
}
if (mFocused != null) {
return mFocused.findFocus(); // 直接返回焦点view
}
return null;
}
View的findFocus方法如下:
public View findFocus() {
return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
}
判断view是否获取焦点的isFocused()方法, (mPrivateFlags & PFLAG_FOCUSED) != 0 和view 的isFocused()方法是一致的。
@ViewDebug.ExportedProperty(category = "focus")
public boolean isFocused() {
return (mPrivateFlags & PFLAG_FOCUSED) != 0;
}
上面我们可以看出,isFocused()方法的作用是判断view是否已经获取焦点,如果viewGroup已经获取到了焦点,那么返回本身即可,否则通过mFocused的findFocus()方法来找焦点。mFocused其实就是ViewGroup中获取焦点的子view,如果mView不是ViewGourp的话,findFocus其实就是判断本身是否已经获取焦点,如果已经获取焦点了,返回本身。
再回到上面的processKeyEvent方法中,如果findFocus方法返回的mFocused不为空,说明找到了当前获取焦点的view(mFocused),接着focusSearch会把direction(遥控器按键按下的方向)作为参数,找到特定方向下一个将要获取焦点的view,最后如果该view不为空,那么就让该view获取焦点。如上面注释“根据按键方向查找焦点”
在此方法里我们会看到focusSearch方法,来看看它的源码:
@Override
public View focusSearch(View focused, int direction) {
if (isRootNamespace()) {
// root namespace means we should consider ourselves the top of the
// tree for focus searching; otherwise we could be focus searching
// into other tabs. see LocalActivityManager and TabHost for more info
return FocusFinder.getInstance().findNextFocus(this, focused, direction);
} else if (mParent != null) {
return mParent.focusSearch(focused, direction);
}
return null;
}
可以看出focusSearch其实是一层一层地网上调用父View的focusSearch方法,直到当前view是根布局(isRootNamespace()方法),通过注释可以知道focusSearch最终会调用DecorView的focusSearch方法。而DecorView的focusSearch方法找到的焦点view是通过FocusFinder来找到的。
@Override
public View focusSearch(View focused, int direction) {
if (isRootNamespace()) {
// root namespace means we should consider ourselves the top of the
// tree for focus searching; otherwise we could be focus searching
// into other tabs. see LocalActivityManager and TabHost for more info
return FocusFinder.getInstance().findNextFocus(this, focused, direction);
} else if (mParent != null) {
return mParent.focusSearch(focused, direction);
}
return null;
}
FocusFinder是什么?
它其实是一个实现 根据给定的按键方向,通过当前的获取焦点的View,查找下一个获取焦点的view这样算法的类。焦点没有被拦截的情况下,Android框架焦点的查找最终都是通过FocusFinder类来实现的。
FocusFinder是如何通过findNextFocus方法寻找焦点的?
一层一层往下看,后面会执行findNextUserSpecifiedFocus()方法,这个方法会执行focused(即当前获取焦点的View)的findUserSetNextFocus方法,如果该方法返回的View不为空,且isFocusable = true && isInTouchMode() = true的话,FocusFinder找到的焦点就是findNextUserSpecifiedFocus()返回的View。
private View findNextUserSpecifiedFocus(ViewGroup root, View focused, int direction) {
// check for user specified next focus
//优先查找用户指定的下一个可获取焦点的view
//即用户在XML中或代码中指定的下一个获取焦点view的ID值来查找
View userSetNextFocus = focused.findUserSetNextFocus(root, direction);
if (userSetNextFocus != null && userSetNextFocus.isFocusable()
&& (!userSetNextFocus.isInTouchMode()
|| userSetNextFocus.isFocusableInTouchMode())) {
return userSetNextFocus;
}
return null;
}
findNextFocus会优先根据XML里设置的下一个将获取焦点的View ID值来寻找将要获取焦点的View。 我们在xml里这么设置,来指定对应方向(上下左右)上的下一个焦点view:
<SeekBar
android:id="@+id/seek"
android:layout_width="match_parent"
android:layout_height="10dp"
android:focusable="true"
android:nextFocusLeft="@+id/leftView"
android:nextFocusRight="@+id/seek"
android:nextFocusUp="@+id/iv_poster"
android:nextFocusDown="@+id/tv_collect"/>
如果按下Left键,那么便会通过nextFocusLeft值里的View Id值去找下一个获取焦点的View。如上会找leftView。
View findUserSetNextFocus(View root, @FocusDirection int direction) {
switch (direction) {
case FOCUS_LEFT:
if (mNextFocusLeftId == View.NO_ID) return null;
return findViewInsideOutShouldExist(root, mNextFocusLeftId);
case FOCUS_RIGHT:
if (mNextFocusRightId == View.NO_ID) return null;
return findViewInsideOutShouldExist(root, mNextFocusRightId);
case FOCUS_UP:
if (mNextFocusUpId == View.NO_ID) return null;
return findViewInsideOutShouldExist(root, mNextFocusUpId);
case FOCUS_DOWN:
if (mNextFocusDownId == View.NO_ID) return null;
return findViewInsideOutShouldExist(root, mNextFocusDownId);
case FOCUS_FORWARD:
if (mNextFocusForwardId == View.NO_ID) return null;
return findViewInsideOutShouldExist(root, mNextFocusForwardId);
case FOCUS_BACKWARD: {
if (mID == View.NO_ID) return null;
final int id = mID;
return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
@Override
public boolean apply(View t) {
return t.mNextFocusForwardId == id;
}
});
}
}
return null;
}
请求获取焦点
搜索到下一个获取焦点的view后,调用该view.requestFocus(direction, mTempRect)方法
注意:调用requestFocus(direction, mTempRect)需要区分调用者。 如果是ViewGroup,则会更加焦点获取策略,实现父View和子View之间获取焦点的优先级。 如下是ViewGroup.java 和View.java 中requestFocus方法是实现:
/**
* {@inheritDoc}
*
* ViewGroup请求焦点的方法
*
* ViewGroup重新了View的该方法,实现了获取焦点顺序的拦截。可根据不同的策略,实现父View和子View之间获取焦点的优先级。
* <p>
* 通过FOCUS_BEFORE_DESCENDANTS,父View优先获取焦点,配合重写addFocusables()方法,实现焦点记忆功能
* <p>
* Looks for a view to give focus to respecting the setting specified by
* {@link #getDescendantFocusability()}.
* <p>
* Uses {@link #onRequestFocusInDescendants(int, android.graphics.Rect)} to
* find focus within the children of this group when appropriate.
*
* @see #FOCUS_BEFORE_DESCENDANTS
* @see #FOCUS_AFTER_DESCENDANTS
* @see #FOCUS_BLOCK_DESCENDANTS
* @see #onRequestFocusInDescendants(int, android.graphics.Rect)
*/
@Override
public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
if (DBG) {
System.out.println(this + " ViewGroup.requestFocus direction="
+ direction);
}
int descendantFocusability = getDescendantFocusability();
//以下代码如果是调用super.requestFocus(direction, previouslyFocusedRect),表示viewGroup自己处理焦点事件
boolean result;
switch (descendantFocusability) {
//直接阻止后代获取焦点,自己处理请求焦点的逻辑
case FOCUS_BLOCK_DESCENDANTS:
result = super.requestFocus(direction, previouslyFocusedRect);
break;
//可优先于后代获取焦点,自己不处理时才交给后代处理
case FOCUS_BEFORE_DESCENDANTS: {
final boolean took = super.requestFocus(direction, previouslyFocusedRect);
result = took ? took : onRequestFocusInDescendants(direction,
previouslyFocusedRect);
break;
}
//将获取焦点的权利优先交给后代,后代都不消费时,自己在处理
case FOCUS_AFTER_DESCENDANTS: {
final boolean took = onRequestFocusInDescendants(direction, previouslyFocusedRect);
result = took ? took : super.requestFocus(direction, previouslyFocusedRect);
break;
}
default:
throw new IllegalStateException(
"descendant focusability must be one of FOCUS_BEFORE_DESCENDANTS,"
+ " FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS but is "
+ descendantFocusability);
}
if (result && !isLayoutValid() && ((mPrivateFlags & PFLAG_WANTS_FOCUS) == 0)) {
mPrivateFlags |= PFLAG_WANTS_FOCUS;
}
return result;
}
View.java中的requestFocus:
public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
return requestFocusNoSearch(direction, previouslyFocusedRect);
}
//直接请求获取焦点,不再搜索
private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
//在该方法中会对控件的当前状态进行判断, 如果不符合获取焦点的前提则直接返回false告知调用方, 控件不会获取焦点
//只要符合前提就会继续执行, 最终必定返回true, 不论当前控件的焦点状态是否有改变
// need to be focusable
if (!canTakeFocus()) {
return false;
}
// need to be focusable in touch mode if in touch mode
if (isInTouchMode() &&
(FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
return false;
}
// need to not have any parents blocking us
//如果该View的父View阻止其获取焦点,则直接返回false
if (hasAncestorThatBlocksDescendantFocus()) {
return false;
}
if (!isLayoutValid()) {
mPrivateFlags |= PFLAG_WANTS_FOCUS;
} else {
clearParentsWantFocus();
}
//framework内部处理获得焦点核心
handleFocusGainInternal(direction, previouslyFocusedRect);
return true;
}
/**
*
* framework处理获取焦点的内部核心逻辑
* Give this view focus. This will cause
* {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
*
* Note: this does not check whether this {@link View} should get focus, it just
* gives it focus no matter what. It should only be called internally by framework
* code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
*
* @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
* focus moved when requestFocus() is called. It may not always
* apply, in which case use the default View.FOCUS_DOWN.
* @param previouslyFocusedRect The rectangle of the view that had focus
* prior in this View's coordinate system.
*/
void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
if (DBG) {
System.out.println(this + " requestFocus()");
}
if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
mPrivateFlags |= PFLAG_FOCUSED;
//getRootView() 获取到的是DecorView,即在整个视图树中查找当前已经获取焦点的view
View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
if (mParent != null) {
//层层向上递归,通知父view 我获取了焦点
mParent.requestChildFocus(this, this);
updateFocusedInCluster(oldFocus, direction);
}
if (mAttachInfo != null) {
//通知View树上焦点全局监听者
mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
}
//通知view自己获得焦点,重写该方法,可监听view自己焦点状态变更
onFocusChanged(true, direction, previouslyFocusedRect);
//刷新view drawable状态
refreshDrawableState();
}
}
焦点变更逐层递归向上级通知
View获取到焦点后,会调用mParent.requestChildFocus(this, focused)逐层递归向上级通知。
ViewGroup.java中代码如下:
@Override
public void requestChildFocus(View child, View focused) {
//如果入参 child==focused 为true,即代表 this 是focused 的直接父view
if (DBG) {
System.out.println(this + " requestChildFocus()");
}
if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) {
return;
}
// Unfocus us, if necessary
//如果有必要,清除焦点
super.unFocus(focused);
// We had a previous notion of who had focus. Clear it.
if (mFocused != child) {
if (mFocused != null) {
//如果之前有view获取焦点,取消焦点
mFocused.unFocus(focused);
}
//记录获得焦点的view或包含焦点的viewGroup
mFocused = child;
}
if (mParent != null) {
//层层向上递归,通知父view,我的子view获取了焦点
//如果入参 child==focused 为true,即代表 this 是focused 的直接父view
mParent.requestChildFocus(this, focused);
}
}
1.如果一个View在XML布局中设置了focusable = true && isInTouchMode = true,那么这个View会优先获取焦点。
2. 通过设置nextFocusLeft,nextFocusRight,nextFocusUp,nextFocusDown值可以控制View的下一个焦点。
3.FocusSearch 一层层上去,调用 FocusFinder.getInstance().findNextFocus… … 后,在addFocusables 下,将所有带焦点属性的 view 全部加到数组里面去,然后通用方向,位置等查找相近的view. 最后找到目标view