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 tlFocusFinder =
            new ThreadLocal() {
                @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 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 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 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 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 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此时有焦点,按下右键时会怎么样呢?

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

实际上判断的依据和下图中的画的各种虚线有关
Android TV开发按键与焦点深入分析(三)--按键事件转换成焦点移动的过程_第2张图片
foucs_right

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

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

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

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

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


Android TV开发按键与焦点深入分析(三)--按键事件转换成焦点移动的过程_第3张图片
foucs_right

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





    
    
    
    
    

你可能感兴趣的:(Android TV开发按键与焦点深入分析(三)--按键事件转换成焦点移动的过程)