Android TV开发按键与焦点深入分析(三)--按键事件转换成焦点移动的过程

上两篇文章分别单独分析了KeyEvent在View树中分发View获得焦点的过程,实际上这两个并不是独立的,当我们按下按键的时候会发现如果我们不拦截按键事件,按键事件就会转换成焦点View的切换,现在就开始分析这个转换的过程。

1.ViewRootImpl中的整体过程

第一篇中提到过KeyEvent在View树中分发是有Boolean返回值的,代码注解如下:

View中
/**
    * Dispatch a key event to the next view on the focus path. This path runs
    * from the top of the view tree down to the currently focused view. If this
    * view has focus, it will dispatch to itself. Otherwise it will dispatch
    * the next node down the focus path. This method also fires any key
    * listeners.
    *
    * @param event The key event to be dispatched.
    * @return True if the event was handled, false otherwise.
    */
   public boolean dispatchKeyEvent(KeyEvent event) 

返回true代表这个按键事件已经被消耗掉了,false代表还没被消耗。默认返回的是fasle,只有我们在这个过程中想要拦截、处理了按键事件,才会返回true。
最后会把这个结果向上一层一层地反馈到按键事件产生的位置,这个位置就是ViewRootImpl的processKeyEvent方法中,如下:

ViewRootImpl中
private int processKeyEvent(QueuedInputEvent q) {
            final KeyEvent event = (KeyEvent)q.mEvent;

            ......

            // Deliver the key to the view hierarchy.
            if (mView.dispatchKeyEvent(event)) {//View树中分发按键事件
                return FINISH_HANDLED;//被处理了
            }
            //没被处理  
            .......
            // Handle automatic focus changes.
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (groupNavigationDirection != 0) {
                    if (performKeyboardGroupNavigation(groupNavigationDirection)) {
                        return FINISH_HANDLED;
                    }
                } else {//寻找焦点View
                    if (performFocusNavigation(event)) {
                        return FINISH_HANDLED;
                    }
                }
            }
}

mView就是DecorView,是否已被消耗的结果的终点就是这里。如果是被消耗了就直接返回,没有,那就调用performFocusNavigation方法,从方法名字就可以看出这个方法就是要将按键事件转换成焦点的移动,方法如下:

ViewRootImpl中
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) {
                View focused = mView.findFocus();//找出此时这个有焦点的View
                if (focused != null) {
                    //调用它的focusSearch方法,顾名思义寻找这个方向上的下一个获得焦点的View
                    View v = focused.focusSearch(direction);
                    if (v != null && v != focused) {
                        // 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);
                        }
                        //调用它的requestFocus,让它获得焦点
                        if (v.requestFocus(direction, mTempRect)) {
                            playSoundEffect(SoundEffectConstants
                                    .getContantForFocusDirection(direction));
                            return true;
                        }
                    }

                    // Give the focused view a last chance to handle the dpad key.
                    if (mView.dispatchUnhandledMove(focused, direction)) {
                        return true;
                    }
                } else {
                    if (mView.restoreDefaultFocus()) {
                        return true;
                    }
                }
            }
            return false;
        }

这个方法中一气呵成完成了按键事件转换成焦点View变化的全部过程,可以概括为以下4个步骤:

  1. 将按键事件的上下左右转换成焦点移动方向的上下左右
  2. 找出View树中有焦点的View
  3. 调用焦点View的focusSearch方法寻找下一个获得焦点的View
  4. 调用下一个获得焦点的View的requestFocus方法,让它获得焦点

下面分别分析第2、3步的过程,第4步请看上一篇的分析

2.寻找有焦点的View

调用的是View的findFocus方法,ViewGroup和View的findFoucs方法分别如下:

ViewGroup中
@Override
    public View findFocus() {
        if (isFocused()) {
            return this;
        }
        if (mFocused != null) {
            return mFocused.findFocus();
        }
        return null;
    }    
View中
    public boolean isFocused() {
        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
    }
View中
    public View findFocus() {
        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
    }

寻找的依据就是上一篇中分析的PFLAG_FOCUSED标志位以及ViewGroup的mFocused成员变量,首先是ViewGroup判断自己是不是有焦点,然后再判断自己是不是包含了有焦点的子View,多次按照焦点的路径遍历就找出了焦点View。

3.寻找下一个获得焦点的View

View的focusSearch方法

此刻已经找出了焦点View,需要调用它的focusSearch去寻找下一个焦点View,View的focusSearch方法如下:

View中
    public View focusSearch(@FocusRealDirection int direction) {
        if (mParent != null) {
            return mParent.focusSearch(this, direction);
        } else {
            return null;
        }
    }

直接调用了它的父View的方法,如下:

ViewGroup中
@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;
    }
    

ViewGroup重写了这个方法,如果自己是RootNamespace那就调用FocusFinder去寻找View,但什么时候isRootNamespace()成立,我现在还没遇到过,所以一般情况下最后会调用到ViewRootImpl的focusSearch方法,这个方法如下:

ViewRootImpl中 
@Override
    public View focusSearch(View focused, int direction) {
        checkThread();
        if (!(mView instanceof ViewGroup)) {
            return null;
        }
        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
    }

殊途同归,最后还是调用了FocusFinder去寻找View,看来寻找下一个焦点View的重任全部都封装在了这个FocusFinder类中。

FocusFinder单例

 private static final ThreadLocal<FocusFinder> tlFocusFinder =
            new ThreadLocal<FocusFinder>() {
                @Override
                protected FocusFinder initialValue() {
                    return new FocusFinder();
                }
            };

    /**
     * Get the focus finder for this thread.
     */
    public static FocusFinder getInstance() {
        return tlFocusFinder.get();
    }

值得注意的是FocusFinder居然是线程单例的,而不是进程单例的,这样做的原因大概是一方面发挥单例优势,避免频繁创建FocusFinder,毕竟这是一个比较基本的功能,节约资源提高效率;另一方面,万一其他线程也要调用FocusFinder去做一些寻找View的事情,如果进程单例那不就影响主线程的效率了?所以线程单例最合适吧。

添加所有可以获得焦点的View

言归正传,继续看它的findNextFocus方法,如下:

FocusFinder中
private View findNextFocus(ViewGroup root, View focused, Rect focusedRect, int direction) {
       View next = null;
       //找出焦点跳转View的范围
       ViewGroup effectiveRoot = getEffectiveRoot(root, focused);
       if (focused != null) {//找出在xml中指定的该方向的下一个获得焦点的View
           next = findNextUserSpecifiedFocus(effectiveRoot, focused, direction);
       }
       if (next != null) {//指定了直接返回
           return next;
       }
       ArrayList<View> focusables = mTempList;
       try {
           focusables.clear();
           //从最顶点,将所有可以获得焦点的View添加到focusables中
           effectiveRoot.addFocusables(focusables, direction);
           if (!focusables.isEmpty()) {
               //从中找出下一个可以获得焦点的View
               next = findNextFocus(effectiveRoot, focused, focusedRect, direction, focusables);
           }
       } finally {
           focusables.clear();
       }
       return next;
   }

首先找出焦点跳转的View的范围,我这里测试时effectiveRoot就是DecorView,也就是整个View树中View都在考虑的范围内。然后调用findNextUserSpecifiedFocus方法去获取我们手动为这个View设置的上下左右的焦点View,对应xml布局中的android:nextFocusXX

            android:nextFocusDown="@id/textView"
            android:nextFocusLeft="@id/textView"
            android:nextFocusRight="@id/textView"
            android:nextFocusUp="@id/textView"

如果设置了,那就直接返回设置的View,没有则继续寻找,addFocusables方法把View树中所有可能获得焦点的View都放进了focusables这个list中。
ViewGroup中的addFocusables方法如下:

ViewGroup中
    @Override
    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
        final int focusableCount = views.size();

        final int descendantFocusability = getDescendantFocusability();
        final boolean blockFocusForTouchscreen = shouldBlockFocusForTouchscreen();
        final boolean focusSelf = (isFocusableInTouchMode() || !blockFocusForTouchscreen);

        if (descendantFocusability == FOCUS_BLOCK_DESCENDANTS) {//拦截了焦点,只判断、添加自己
            if (focusSelf) {
                super.addFocusables(views, direction, focusableMode);
            }
            return;
        }

        if (blockFocusForTouchscreen) {
            focusableMode |= FOCUSABLES_TOUCH_MODE;
        }
        //在所有子View之前添加自己到views
        if ((descendantFocusability == FOCUS_BEFORE_DESCENDANTS) && focusSelf) {
            super.addFocusables(views, direction, focusableMode);
        }

        int count = 0;
        final View[] children = new View[mChildrenCount];
        //挑出可见的View
        for (int i = 0; i < mChildrenCount; ++i) {
            View child = mChildren[i];
            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
                children[count++] = child;
            }
        }
        //对所有子View排序
        FocusFinder.sort(children, 0, count, this, isLayoutRtl());
        for (int i = 0; i < count; ++i) {//把所有子View按顺序添加到views
            children[i].addFocusables(views, direction, focusableMode);
        }

        // When set to FOCUS_AFTER_DESCENDANTS, we only add ourselves if
        // there aren't any focusable descendants.  this is
        // to avoid the focus search finding layouts when a more precise search
        // among the focusable children would be more interesting.
        if ((descendantFocusability == FOCUS_AFTER_DESCENDANTS) && focusSelf
                && focusableCount == views.size()) {
            super.addFocusables(views, direction, focusableMode);
        }
    }

如果ViewGroup拦截焦点,那就不用再考虑子View了;如果ViewGroup在子View之前获得焦点,那就先添加,反之后添加;对于兄弟View,在添加之前还要对它们进行排序,排序的依据是从上到下、从左到右。

View的addFocusables方法

    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
            @FocusableMode int focusableMode) {
        if (views == null) {
            return;
        }
        if (!canTakeFocus()) {
            return;
        }
        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
                && !isFocusableInTouchMode()) {
            return;
        }
        views.add(this);
    }

直接判断自己是否可以获得焦点,可以的话就把自己加到views中去。

到这里所有的可以获得焦点的View 都被添加到了focusables中去了,在这个过程中与方向还没有关系,只是枚举添加了所有可能的View。

寻找最优View

有了focusables列表,这时调用同名方法findNextFocus在focusables找出最合适的那个View,方法如下:

private View findNextFocus(ViewGroup root, View focused, Rect focusedRect,
            int direction, ArrayList<View> focusables) {
        if (focused != null) {
            if (focusedRect == null) {
                focusedRect = mFocusedRect;
            }
            // fill in interesting rect from focused
            focused.getFocusedRect(focusedRect);
            //将focused的坐标变成rootView下的坐标
            root.offsetDescendantRectToMyCoords(focused, focusedRect);
        } else {
           ......
        }

        switch (direction) {
            case View.FOCUS_FORWARD:
            case View.FOCUS_BACKWARD:
                return findNextFocusInRelativeDirection(focusables, root, focused, focusedRect,
                        direction);
            case View.FOCUS_UP:
            case View.FOCUS_DOWN:
            case View.FOCUS_LEFT:
            case View.FOCUS_RIGHT:
     
                return findNextFocusInAbsoluteDirection(focusables, root, focused,
                        focusedRect, direction);
            default:
                throw new IllegalArgumentException("Unknown direction: " + direction);
        }
    }

到这里,寻找的才与方向有关,下面的分析以按右键为例,对应的是View.FOCUS_RIGHT,调用了findNextFocusInAbsoluteDirection方法:

View findNextFocusInAbsoluteDirection(ArrayList<View> focusables, ViewGroup root, View focused,
            Rect focusedRect, int direction) {
        // initialize the best candidate to something impossible
        // (so the first plausible view will become the best choice)
        mBestCandidateRect.set(focusedRect);
        switch(direction) {
            case View.FOCUS_LEFT:
                mBestCandidateRect.offset(focusedRect.width() + 1, 0);
                break;
            case View.FOCUS_RIGHT://向右寻找时,将初始的位置设为当前View的最左边
                mBestCandidateRect.offset(-(focusedRect.width() + 1), 0);
                break;
            case View.FOCUS_UP:
                mBestCandidateRect.offset(0, focusedRect.height() + 1);
                break;
            case View.FOCUS_DOWN:
                mBestCandidateRect.offset(0, -(focusedRect.height() + 1));
        }

        View closest = null;

        int numFocusables = focusables.size();
        //遍历所有的可获得焦点的View
        for (int i = 0; i < numFocusables; i++) {
            View focusable = focusables.get(i);
            //排除自己
            // only interested in other non-root views
            if (focusable == focused || focusable == root) continue;
            //获得这个View的rect,并把它调整到和focusedRect一致
            // get focus bounds of other view in same coordinate system
            focusable.getFocusedRect(mOtherRect);
            root.offsetDescendantRectToMyCoords(focusable, mOtherRect);
            //判断这个View是不是比mBestCandidateRect更优
            if (isBetterCandidate(direction, focusedRect, mOtherRect, mBestCandidateRect)) {
                //更优,那么将它设置成mBestCandidateRect,并将closest赋值
                mBestCandidateRect.set(mOtherRect);
                closest = focusable;
            }
        }
        return closest;
    }

实际上寻找的过程就是在比较各个View的占用区域的相对关系,这里首先设置了一个mBestCandidateRect代表最合适的View的区域,对于向右,是焦点View左边间距一像素的同等大小的一个区域,显然这是最不合适的区域,这只是一个初始值。然后就开始遍历所有可能的View,调用isBetterCandidate方法去判断,这里就不展开这个方法,太啰嗦了,用下面的图代替。
假如下图中View1此时有焦点,按下右键时会怎么样呢?


实际上判断的依据和下图中的画的各种虚线有关
foucs_right

按下右键,初始的最佳区域就是红色虚线框的位置,显示是最不适合的,然后再遍历所有的可能的View,满足以下两点才可以击败红色虚线框的位置成为待选的View:

  1. 以紫色虚线作为标准,View的右边线必须在紫色虚线的右边
  2. 以黑色虚线作为标准,View的左边线必须在黑色虚线的右边

显然View2和View3都满足,这时就需要进一步的比较了,进一步比较需要参考View的上下两边,满足以下两点的最优:

  1. View的下边线在上面的那条蓝色虚线之下
  2. View的上边线在下面的那条蓝色虚线之上

也就是这个View的与焦点View在上下两边上有重叠的区域就可以了,所以View3是最优的位置,View3将获得焦点。
还有一种情况,要是两个View都与焦点View在上下两边有重叠的区域,那谁更优呢?如下:


foucs_right

对于向右寻找焦点,这时判断的依据就和图中的两个距离箭头major和minor的长度有关,计算的公式distance=13*major^2+minor^2,distance越小越有优,13是一个常量系数,表示以左右间距作为主要的判断依据,但不排除上下间距逆袭的可能,所以越靠近焦点View的中心,就越有可能获得焦点。
调试的布局如下,可以微微调整bias,验证结论。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
        android:layout_height="match_parent"
        android:layout_width="match_parent">


    <TextView
            android:text="View1"
            android:background="@drawable/bg"
            android:focusable="true"
            android:gravity="center"
            android:layout_width="55dp"
            android:layout_height="344dp"
            android:id="@+id/textView"
            app:layout_constraintEnd_toStartOf="@id/guideline2"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintHorizontal_bias="0.99"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"/>
    <TextView
            android:text="View2"
            android:background="@drawable/bg"
            android:focusable="true"
            android:layout_width="60dp"
            android:gravity="center"
            android:layout_height="50dp"
            android:id="@+id/textView2"
            app:layout_constraintStart_toStartOf="@+id/guideline2"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintHorizontal_bias="0.1"
            app:layout_constraintBottom_toTopOf="@+id/guideline"
            app:layout_constraintVertical_bias="0.7"/>
    <TextView
            android:text="View3"
            android:background="@drawable/bg"
            android:focusable="true"
            android:layout_width="60dp"
            android:gravity="center"
            android:layout_height="50dp"
            android:id="@+id/textView3"
            app:layout_constraintStart_toStartOf="@+id/guideline2"
            app:layout_constraintVertical_bias="0.3"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="@+id/guideline"
            app:layout_constraintHorizontal_bias="0.1"
            app:layout_constraintBottom_toBottomOf="parent"/>
    <android.support.constraint.Guideline
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintGuide_percent="0.3"
            android:id="@+id/guideline2"
            android:orientation="vertical"/>
    <android.support.constraint.Guideline
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintGuide_percent="0.5"
            android:id="@+id/guideline"
            android:orientation="horizontal"/>
</android.support.constraint.ConstraintLayout>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容