Android强行进阶—按键事件&焦点事件攻略,Android程序员最大的悲哀是什么

handled = TextKeyListener.getInstance().onKeyDown(
null, mDefaultKeySsb, keyCode, event);
if (handled && mDefaultKeySsb.length() > 0) {
final String str = mDefaultKeySsb.toString();
clearSpannable = true;
switch (mDefaultKeyMode) {
case DEFAULT_KEYS_DIALER:
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(“tel:” + str));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
case DEFAULT_KEYS_SEARCH_LOCAL:
startSearch(str, false, null, false);
break;
case DEFAULT_KEYS_SEARCH_GLOBAL:
startSearch(str, false, null, true);
break;
}
}
}
if (clearSpannable) {
mDefaultKeySsb.clear();
mDefaultKeySsb.clearSpans();
Selection.setSelection(mDefaultKeySsb,0);
}
return handled;
}
}

public boolean onKeyLongPress(int keyCode, KeyEvent event) {
return false;
}

public boolean onKeyUp(int keyCode, KeyEvent event) {
if (getApplicationInfo().targetSdkVersion

= Build.VERSION_CODES.ECLAIR) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
&& !event.isCanceled()) {
onBackPressed();
return true;
}
}
return false;
}
复制代码

而View中实现:

//View
public boolean onKeyDown(int keyCode, KeyEvent event) {
//KEYCODE_DPAD_CENTER、KEYCODE_ENTER、
//KEYCODE_SPACE、KEYCODE_NUMPAD_ENTER都返回ture,其他返回false
if (KeyEvent.isConfirmKey(keyCode)) {
//当前View是DISABLED状态直接返回false
if ((mViewFlags & ENABLED_MASK) == DISABLED) {
return true;
}

if (event.getRepeatCount() == 0) {
final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
|| (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
final float x = getWidth() / 2f;
final float y = getHeight() / 2f;
if (clickable) {
//标记为Pressed,例如根据状态改变背景
setPressed(true, x, y);
}
//长按检测
checkForLongClick(0, x, y);
return true;
}
}
}

return false;
}

public boolean onKeyUp(int keyCode, KeyEvent event) {
if (KeyEvent.isConfirmKey(keyCode)) {
if ((mViewFlags & ENABLED_MASK) == DISABLED) {
return true;
}
if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
setPressed(false);

if (!mHasPerformedLongPress) {
removeLongPressCallback();
if (!event.isCanceled()) {
return performClickInternal();
}
}
}
}
return false;
}
复制代码

在DecorView的superDispatchKeyEvent()函数最后一行,如果View层次结构不消费事件,那么会调用ViewRootImpl对象的dispatchUnhandledKeyEvent()函数,这里主要是将未被消费的KeyEvent分发给注册了处理所有KeyEvent的处理者(监听器)

//ViewRootImpl.java

private final UnhandledKeyManager mUnhandledKeyManager
=new UnhandledKeyManager();

public boolean dispatchUnhandledKeyEvent(KeyEvent event) {
return mUnhandledKeyManager.dispatch(mView, event);
}

boolean dispatch(View root, KeyEvent event) {
if (mDispatched) {
return false;
}
View consumer;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, “UnhandledKeyEvent dispatch”);
mDispatched = true;
//将未处理的KeyEvent进行分发,如果有View消费该事件,则返回该
//View
consumer = root.dispatchUnhandledKeyEvent(event);
//用于追踪该事件
if (event.getAction() == KeyEvent.ACTION_DOWN) {
int keycode = event.getKeyCode();
if (consumer != null && !KeyEvent.isModifierKey(keycode)) {
mCapturedKeys.put(keycode, new WeakReference<>(consumer));
}
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return consumer != null;
}
复制代码

这里的root是DecorView,但从参数的类型来说,这里root.dispatchUnhandledKeyEvent(event)应该是在View中实现的。

//View.java

View dispatchUnhandledKeyEvent(KeyEvent evt) {
if (onUnhandledKeyEvent(evt)) {
return this;
}
return null;
}

boolean onUnhandledKeyEvent(@NonNull KeyEvent event) {
if (mListenerInfo != null && mListenerInfo.mUnhandledKeyListeners != null) {
//mListenerInfo通过栈的方式保存是否有View设置UnhandledKeyListener,如果有且消费事件,则该DecorView消费该事件
for (int i = mListenerInfo.mUnhandledKeyListeners.size() - 1; i >= 0; --i) {
if (mListenerInfo.mUnhandledKeyListeners.get(i).onUnhandledKeyEvent(this, event)) {
return true;
}
}
}
return false;
}
复制代码

通过上文代码可以知道,我们可以在View中添加addOnUnhandledKeyEventListener(OnUnhandledKeyEventListener)来监听所有未被处理的KeyEvent。会在KeyEvent正常分发未被消费前,且早于Window的Callback被回调。

在DecorView的dispatchKeyEvent()函数,如果View层次结构不消费事件,那么会交给PhoneWindow的onKeyDown()onKeyUp()函数。

//PhoneWindow
protected boolean onKeyDown(int featureId, int keyCode, KeyEvent event) {

final KeyEvent.DispatcherState dispatcher =
mDecor != null ? mDecor.getKeyDispatcherState() : null;
Integer.toHexString(event.getFlags()));

switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_MUTE: {
if (mMediaController != null) {
mMediaController.dispatchVolumeButtonEventAsSystemService(event);
} else {
getMediaSessionManager().dispatchVolumeKeyEventAsSystemService(event,
mVolumeControlStreamType);
}
return true;
}

case KeyEvent.KEYCODE_MEDIA_PLAY:
case KeyEvent.KEYCODE_MEDIA_PAUSE:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_MUTE:
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_MEDIA_STOP:
case KeyEvent.KEYCODE_MEDIA_NEXT:
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
case KeyEvent.KEYCODE_MEDIA_REWIND:
case KeyEvent.KEYCODE_MEDIA_RECORD:
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
if (mMediaController != null) {
if (mMediaController.dispatchMediaButtonEventAsSystemService(event)) {
return true;
}
}
return false;
}

case KeyEvent.KEYCODE_MENU: {
onKeyDownPanel((featureId < 0) ? FEATURE_OPTIONS_PANEL : featureId, event);
return true;
}

case KeyEvent.KEYCODE_BACK: {
if (event.getRepeatCount() > 0) break;
if (featureId < 0) break;
if (dispatcher != null) {
dispatcher.startTracking(event, this);
}
return true;
}

}

return false;
}

protected boolean onKeyUp(int featureId, int keyCode, KeyEvent event) {
final KeyEvent.DispatcherState dispatcher =
mDecor != null ? mDecor.getKeyDispatcherState() : null;
if (dispatcher != null) {
dispatcher.handleUpEvent(event);
}

switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN: {
if (mMediaController != null) {
mMediaController.dispatchVolumeButtonEventAsSystemService(event);
} else {
getMediaSessionManager().dispatchVolumeKeyEventAsSystemService(
event, mVolumeControlStreamType);
}
return true;
}
case KeyEvent.KEYCODE_VOLUME_MUTE: {
getMediaSessionManager().dispatchVolumeKeyEventAsSystemService(
event, AudioManager.USE_DEFAULT_STREAM_TYPE);
return true;
}

case KeyEvent.KEYCODE_MEDIA_PLAY:
case KeyEvent.KEYCODE_MEDIA_PAUSE:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_MUTE:
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_MEDIA_STOP:
case KeyEvent.KEYCODE_MEDIA_NEXT:
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
case KeyEvent.KEYCODE_MEDIA_REWIND:
case KeyEvent.KEYCODE_MEDIA_RECORD:
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
if (mMediaController != null) {
if (mMediaController.dispatchMediaButtonEventAsSystemService(event)) {
return true;
}
}
return false;
}

case KeyEvent.KEYCODE_MENU: {
onKeyUpPanel(featureId < 0 ? FEATURE_OPTIONS_PANEL : featureId,
event);
return true;
}

case KeyEvent.KEYCODE_BACK: {
if (featureId < 0) break;
if (event.isTracking() && !event.isCanceled()) {
if (featureId == FEATURE_OPTIONS_PANEL) {
PanelFeatureState st = getPanelState(featureId, false);
if (st != null && st.isInExpandedMode) {
reopenMenu(true);
return true;
}
}
closePanel(featureId);
return true;
}
break;
}

case KeyEvent.KEYCODE_SEARCH: { /*

if (isNotInstantAppAndKeyguardRestricted()) {
break;
}
if ((getContext().getResources().getConfiguration().uiMode
& Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_WATCH) {
break;
}
if (event.isTracking() && !event.isCanceled()) {
launchDefaultSearch(event);
}
return true;
}

case KeyEvent.KEYCODE_WINDOW: {
if (mSupportsPictureInPicture && !event.isCanceled()) {
getWindowControllerCallback().enterPictureInPictureModeIfPossible();
}
return true;
}
}

return false;
}
复制代码

从上面可以看到,PhoneWindow也只对一些物理按键做了处理,如果PhoneWindow和View、Activity都没有消费事件,那么ViewPostImeInputStage对象通过系统算法自动寻找焦点了。

总结一下:

  1. 监听器的优先级高于Callback的回调,也就是说OnKeyListener的函数优先Callback的onKeyDown等等函数的回调。
  2. View的Callback回调要早于Activity,Activity的回调早于PhoneWindow。
  3. 优先级高的消费KeyEvent,优先级低的不再受理该事件。

下面通过时序图对上文KeyEvent做一个整体流程的阐释(虽然不能准备表达意思)

Android强行进阶—按键事件&焦点事件攻略,Android程序员最大的悲哀是什么_第1张图片

在图表示在KeyEvent在DecorView开始不拦截最终在View的OnKeyListener或Callback对象被消费的过程。

参考文章

系统自动寻找焦点

回到梦开始的地方ViewPostImeInputStage对象的processKeyEvent()函数的末尾,在自动处理焦点的地方,会调用performFocusNavigation()函数来寻找下个获得焦点的View。

//ViewRootImpl.java

private boolean performFocusNavigation(KeyEvent event) {

int direction = 0;
//从下面代码可以看出,switch语句在此的主要作用是判断焦点的方向
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对象,查找出当前获得焦点的View
View focused = mView.findFocus();
if (focused != null) {
//分析二
//在当前获得焦点View通过指定方向搜索下一个获得焦点的View
View v = focused.focusSearch(direction);
if (v != null && v != focused) {
focused.getFocusedRect(mTempRect);
if (mView instanceof ViewGroup) {
((ViewGroup) mView).offsetDescendantRectToMyCoords(
focused, mTempRect);
((ViewGroup) mView).offsetRectIntoDescendantCoords(
v, mTempRect);
}
if (v.requestFocus(direction, mTempRect)) {
playSoundEffect(SoundEffectConstants
.getContantForFocusDirection(direction));
return true;
}
}

//给DecorView最后一次处理焦点的机会
if (mView.dispatchUnhandledMove(focused, direction)) {
reAndroid强行进阶—按键事件&焦点事件攻略,Android程序员最大的悲哀是什么_第2张图片
turn true;
}
} else {
//如果没有View获得焦点
if (mView.restoreDefaultFocus()) {
return true;
}
}
}
return false;
}
复制代码

在分析一处,通过DecorView对象mView来查找已获得焦点的View,findFocus()函数在ViewGroup和View都有实现,而DecorView继承自ViewGroup。这里其实进入了View的层次结果查找已获得焦点的View.

//ViewGroup.java
@Override
public View findFocus() {

if (isFocused()) {
return this;
}

if (mFocused != null) {
//mFocused表示获得焦点的View,有可能是ViewGroup,也有可能是具体的View
return mFocused.findFocus();
}
return null;
}

//View.java
public View findFocus() {
return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
}

public boolean isFocused() {
return (mPrivateFlags & PFLAG_FOCUSED) != 0;
}
复制代码

对于ViewGroup来说,如果本身获得焦点则直接返回自身即可,否则继续通过mFocused.findFocus()函数继续查找已获得焦点的View。具体的View是否获得焦点与ViewGroup的判断条件是一致的,判断PFLAG_FOCUSED标志位,也就是我们调用View的focuesabe=true,如果设置,则返回该View,否则返回null,表示没有View获得焦点。

假设寻找到了已获得焦点的View,那么下面就是寻找下一个获得焦点的View。也就是ViewPostImeInputStage对象的performFocusNavigation()函数分析二的代码。由于focused对象有可能是ViewGroup,也有可能是具体的View。一起看看它两的实现。

//View
//具体View的实现非常的简单,如果有父视图ViewGroup,则在俯视图在寻找,
//否则返回null
public View focusSearch(@FocusRealDirection int direction) {
if (mParent != null) {
return mParent.focusSearch(this, direction);
} else {
return null;
}
}
//ViewGroup.java
@Override
public View focusSearch(View focused, int direction) {
if (isRootNamespace()) { //判断当前ViewGroup是否顶层View,即DecorView
//调用FocusFinder实例findNextFocus进行查找
return FocusFinder.getInstance().findNextFocus(this, focused, direction);
} else if (mParent != null) {
//递归到顶层View
return mParent.focusSearch(focused, direction);
}
return null;
}
复制代码

通过递归方式,从内到外,到布局最外层View,准确说是ViewGroup。然后调用FocusFinder的实例方法findNextFocus()来寻找下一个获得焦点的View。 FocusFinder类通过算法,根据当前获得焦点的View和按键方向来寻找下一个获得焦点的View。

//FocusFinder.java
public final View findNextFocus(ViewGroup root, View focused, int direction) {
return findNextFocus(root, focused, null, direction);
}

private View findNextFocus(ViewGroup root, View focused, Rect focusedRect, int direction) {
View next = null;
ViewGroup effectiveRoot = getEffectiveRoot(root, focused);
if (focused != null) {
//寻找当前获得焦点view是否设置了指定方向的下一个获得焦点的View
next = findNextUserSpecifiedFocus(effectiveRoot, focused, direction);
}
if (next != null) {
return next;
}
ArrayList focusables = mTempList;
try {
focusables.clear();
effectiveRoot.addFocusables(focusables, direction);
if (!focusables.isEmpty()) {
//通过算法寻找最近可获得焦点的View
next = findNextFocus(effectiveRoot, focused, focusedRect, direction, focusables);
}
} finally {
focusables.clear();
}
return next;
}
复制代码

findNextFocus()函数主要通过两种方式来寻找指定方向的下一个获得焦。的View:我们在XML布局或者代码设置特定方向获得焦点的View;通过算法来寻找特定方向可以获得焦点最近的View。

对于方式一,findNextUserSpecifiedFocus()函数的实现如下:

//View.java
//主要作用是判断当前获得焦点的View有没有指定下一个获得焦点View的ID
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() {
@Override
public boolean test(View t) {
return t.mNextFocusForwardId == id;
}
});
}
}
return null;
}
//MatchIdPredicate匹配到相同ID会返回true
private View findViewInsideOutShouldExist(View root, int id) {
if (mMatchIdPredicate == null) {
mMatchIdPredicate = new MatchIdPredicate();
}
mMatchIdPredicate.mId = id;
View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
if (result == null) {
Log.w(VIEW_LOG_TAG, "couldn’t find view with id " + id);
}
return result;
}
//从当前View开始,遍历View的层次结构来的下一个获得焦点的View
public final T findViewByPredicateInsideOut(
View start, Predicate predicate) {
View childToSkip = null;
for (; {
T view = start.findViewByPredicateTraversal(predicate, childToSkip);
if (view != null || start == this) {
return view;
}

ViewParent parent = start.getParent();
if (parent == null || !(parent instanceof View)) {
return null;
}

childToSkip = start;
start = (View) parent;
}
}
//匹配相同ID,返回该View
protected T findViewByPredicateTraversal(Predicate predicate,
View childToSkip) {
if (predicate.test(this)) {
return (T) this;
}
return null;
}
复制代码

在上面的相关方法,主要是通过在View的层次结构中去寻找到和指定id匹配的View。

那么方式二,通过算法来寻找下一个焦点又是如何的呢?

//FocusFinder.java
private View findNextFocus(ViewGroup root, View focused, Rect focusedRect,
int direction, ArrayList focusables) {
if (focused != null) {
if (focusedRect == null) {
focusedRect = mFocusedRect;
}
// fill in interesting rect from focused
focused.getFocusedRect(focusedRect);
root.offsetDescendantRectToMyCoords(focused, focusedRect);
} else {
if (focusedRect == null) {
focusedRect = mFocusedRect;
// make up a rect at top left or bottom right of root
switch (direction) {
case View.FOCUS_RIGHT:
case View.FOCUS_DOWN:
setFocusTopLeft(root, focusedRect);
break;
case View.FOCUS_FORWARD:
if (root.isLayoutRtl()) {
setFocusBottomRight(root, focusedRect);
} else {
setFocusTopLeft(root, focusedRect);
}
break;

case View.FOCUS_LEFT:
case View.FOCUS_UP:
setFocusBottomRight(root, focusedRect);
break;
case View.FOCUS_BACKWARD:
if (root.isLayoutRtl()) {
setFocusTopLeft(root, focusedRect);
} else {
setFocusBottomRight(root, focusedRect);
break;
}
}
}
}
复制代码

对FocusFinder就不作进一步分析了。感兴趣同学可以自己看看源码。

看到这里,估计都很累了,我们想了解也都知道了。

总结

所有的KeyEvent都会优先在View的层次结构分发,然后再通过自动寻找焦点来查找下一个获得焦点的View。这就是为什么在OnKeyListener或Callback相关回调方法返回true消费KeyEvent,下一个View无法获得焦点。

KeyEvent在View的层次结构分发总是从外到里,外层ViewGroup消费KeyEvent,内层的View是无法获得焦点的。这就是为什么我们不想要EditText弹出软键盘,在根布局设置focusable为true的原因。

OnKeyListener的调用要早于KeyEvent.Callback的调用,如果设置了OnKeyListener并消费了KeyEvent,那么Callback相关函数不会再被调用。

另外,想要在KeyEvent分发前处理KeyEvent,例如TV开发处理特殊的按键,可以修改PhoneWindowManagerinterceptKeyBeforeDispatching()函数。

最后的最后,能回答开头的问题么?

作者:新小梦
链接:https://juejin.im/post/5d5d35e3e51d4561ae4da62c

t, focusedRect);
break;
}
}
}
}
复制代码

对FocusFinder就不作进一步分析了。感兴趣同学可以自己看看源码。

看到这里,估计都很累了,我们想了解也都知道了。

总结

所有的KeyEvent都会优先在View的层次结构分发,然后再通过自动寻找焦点来查找下一个获得焦点的View。这就是为什么在OnKeyListener或Callback相关回调方法返回true消费KeyEvent,下一个View无法获得焦点。

KeyEvent在View的层次结构分发总是从外到里,外层ViewGroup消费KeyEvent,内层的View是无法获得焦点的。这就是为什么我们不想要EditText弹出软键盘,在根布局设置focusable为true的原因。

OnKeyListener的调用要早于KeyEvent.Callback的调用,如果设置了OnKeyListener并消费了KeyEvent,那么Callback相关函数不会再被调用。

另外,想要在KeyEvent分发前处理KeyEvent,例如TV开发处理特殊的按键,可以修改PhoneWindowManagerinterceptKeyBeforeDispatching()函数。

最后的最后,能回答开头的问题么?

作者:新小梦
链接:https://juejin.im/post/5d5d35e3e51d4561ae4da62c

你可能感兴趣的:(程序员,架构,移动开发,android)