上一篇分析到了KeyEvent的分发其实就是把事件交给了焦点View处理,那怎么去定义一个View可获得焦点?其实很简单,只需要在xml布局中设置View的focusable属性为true就可以了,那现在就开始分析这个focusable属性究竟是怎么发挥它的作用的。
View的焦点模式
View定义了三种焦点模式,直接看它们在代码中定义:
/**
* This view does not want keystrokes.
*/
public static final int NOT_FOCUSABLE = 0x00000000;
/**
* This view wants keystrokes.
*/
public static final int FOCUSABLE = 0x00000001;
/**
* This view determines focusability automatically. This is the default.
*/
public static final int FOCUSABLE_AUTO = 0x00000010;
/**
* Mask for use with setFlags indicating bits used for focus.
*/
private static final int FOCUSABLE_MASK = 0x00000011;
/**
* The view flags hold various views states.
* {@hide}
*/
@ViewDebug.ExportedProperty(formatToHexString = true)
int mViewFlags;
其中FOCUSABLE_MASK表示foucsable属性占用mViewFlags的bit位置,可以看出mViewFlags中第1位和第5位用来联合表示view的焦点模式,有FOCUSABLE、NOT_FOCUSABLE和FOCUSABLE_AUTO三种焦点模式,第1位控制FOCUSABLE、NOT_FOCUSABLE,第5位单独控制FOCUSABLE_AUTO.
接着看看View的构造方法中解析xml布局设置的focusable属性的过程,主要的代码如下:
View的构造方法中
public View(Context context, @Nullable AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
//设置默认的值
mViewFlags = FOCUSABLE_AUTO;
// Set default values.
viewFlagValues |= FOCUSABLE_AUTO;
viewFlagMasks |= FOCUSABLE_AUTO;
......
for (int i = 0; i < N; i++) {
//获取xml文件中设置的的焦点状态
case com.android.internal.R.styleable.View_focusable:
// (viewFlagValues & ~FOCUSABLE_MASK) 将焦点状态置为空,“与|”将从xml中获取的焦点状态赋值给viewFlagValues
viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a);
//如果viewFlagValues中的焦点状态不再是FOCUSABLE_AUTO,说明焦点状态变了,修改位变化记录mask值
if ((viewFlagValues & FOCUSABLE_AUTO) == 0) {
viewFlagMasks |= FOCUSABLE_MASK;
}
break;
}
.......
if (viewFlagMasks != 0) {
setFlags(viewFlagValues, viewFlagMasks);
}
}
//将xml中设置的焦点状态转换为View自己定义的二进制格式
private int getFocusableAttribute(TypedArray attributes) {
TypedValue val = new TypedValue();
if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
} else {
return val.data;
}
} else {
return FOCUSABLE_AUTO;
}
}
在最开始的时候设置了View的焦点模式为FOCUSABLE_AUTO,在遍历属性时如果xml布局有设置focusable属性,则取出,没有的话依然是FOCUSABLE_AUTO,这样focuable属性就转换成了viewFlagValues中的参数,构造方法最后还调用了setFlags方法设置mViewFlags,这个方法内还处理设置了clickable但没有设置focusable的情况,如下:
View中
void setFlags(int flags, int mask) {
//将flags变化了的bit同步到全局变量mViewFlags中
mViewFlags = (mViewFlags & ~mask) | (flags & mask);
......
// If focusable is auto, update the FOCUSABLE bit.
int focusableChangedByAuto = 0;
//焦点状态是FOCUSABLE_AUTO
if (((mViewFlags & FOCUSABLE_AUTO) != 0)
&& (changed & (FOCUSABLE_MASK | CLICKABLE)) != 0) {
// Heuristic only takes into account whether view is clickable.
final int newFocus;
//View可以被点击,将焦点状态添加FOCUSABLE,否则添加NOT_FOCUSABLE
if ((mViewFlags & CLICKABLE) != 0) {
newFocus = FOCUSABLE;
} else {
newFocus = NOT_FOCUSABLE;
}
mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
.....
}
}
可以看出,如果是FOCUSABLE_AUTO情况,也就是xml文件没设置focusable属性,焦点的模式还与clickable属性有关,如果View是clickable的,那么View是FOCUSABLE,否则是NOT_FOCUSABLE,可以用下面这张表来描述clickable和focusable属性对View的焦点模式的影响
现在可以回答上一篇结束时提的问题了,Android手机应用运行在Android电视上可以响应按键事件吗?如果这个View在xml文件中设置了clickable属性为true那这个View就可以获得焦点,也就可以响应按键事件,如果既没有设置clickable也没有设置focusable为true,那这个View就获取不到焦点,也就响应不了按键事件了。
下面是View提供的两种获得焦点模式的方法
View中
public int getFocusable() {
//只要设置了FOCUSABLE_AUTO就只返回FOCUSABLE_AUTO
return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE;
}
public final boolean isFocusable() {
return FOCUSABLE == (mViewFlags & FOCUSABLE);
}
一般情况我们使用isFocusable方法就OK了,getFocusable方法可以用来在可以获得焦点时判断是clickable导致的,还是focusable设置的.
ViewGroup的焦点模式
上小节分析的View的焦点模式完全适用于ViewGroup,毕竟它也是View的儿子,但由于ViewGroup有子View,为了避免焦点产生歧义,还定义了ViewGroup相对于子View的三种获得焦点的顺序,如下:
/**
在所有子View之前
* This view will get focus before any of its descendants.
*/
public static final int FOCUS_BEFORE_DESCENDANTS = 0x20000;
/**
在所有子View之后
* This view will get focus only if none of its descendants want it.
*/
public static final int FOCUS_AFTER_DESCENDANTS = 0x40000;
/**
拦截所有焦点,不通知子View
* This view will block any of its descendants from getting focus, even
* if they are focusable.
*/
public static final int FOCUS_BLOCK_DESCENDANTS = 0x60000;
//定义mGroupFlags中的第17和18位用来表示这个顺序
private static final int FLAG_MASK_FOCUSABILITY = 0x60000;
protected int mGroupFlags;
ViewGroup的FLAG_MASK_FOCUSABILITY是用来控制焦点在View树中的传递顺序的,顺序有三种:
- FOCUS_BEFORE_DESCENDANTS: 在所有子View之前,自己没获取再给子View
- FOCUS_AFTER_DESCENDANTS: 在所有子View之后,所有子View都没能获得焦点才问下自己能不能
- FOCUS_BLOCK_DESCENDANTS: 不通知子View ,即使自己获取不到
和View的焦点模式一样,获得焦点的顺序也是在构造方法中设置的:
ViewGroup中
private static final int[] DESCENDANT_FOCUSABILITY_FLAGS =
{FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS,
FOCUS_BLOCK_DESCENDANTS};
public ViewGroup(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
......
case R.styleable.ViewGroup_descendantFocusability:
//默认是FOCUS_BEFORE_DESCENDANTS
setDescendantFocusability(DESCENDANT_FOCUSABILITY_FLAGS[a.getInt(attr, 0)]);
break;
}
public void setDescendantFocusability(int focusability) {
switch (focusability) {
case FOCUS_BEFORE_DESCENDANTS:
case FOCUS_AFTER_DESCENDANTS:
case FOCUS_BLOCK_DESCENDANTS:
break;
default:
throw new IllegalArgumentException("must be one of FOCUS_BEFORE_DESCENDANTS, "
+ "FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS");
}
//设置顺序
mGroupFlags &= ~FLAG_MASK_FOCUSABILITY;
mGroupFlags |= (focusability & FLAG_MASK_FOCUSABILITY);
}
从代码中可以发现,如果不写这个属性,ViewGroup设置自己在所有子View之前处理焦点.
View的requestFocus方法
要让一个View获得焦点,需要调用它的requestFocus方法,调用时序图如下(具体的方法可以直接搜索源码):
View先调用自己的canTakeFocus方法确认自己是不是能够获得焦点,这个方法如下:
private boolean canTakeFocus() {
return ((mViewFlags & VISIBILITY_MASK) == VISIBLE)
&& ((mViewFlags & FOCUSABLE) == FOCUSABLE)
&& ((mViewFlags & ENABLED_MASK) == ENABLED)
&& (sCanFocusZeroSized || !isLayoutValid() || hasSize());
}
判断的依据是 : 1.view可见 2.可以获得焦点 3.是enable的 4.有大小
然后递归调用所有父View的hasAncestorThatBlocksDescendantFocus方法,确认父View是不是设置了拦截焦点,如果父View拦截了焦点,自己就不能获得焦点。
如果上面两项都通过了,那就可以名正言顺的获得焦点了,handleFocusGainInternal方法如下:
void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
if (DBG) {
System.out.println(this + " requestFocus()");
}
//修改状态,flag添加PFLAG_FOCUSED,标记自己有焦点
if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
mPrivateFlags |= PFLAG_FOCUSED;
View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
if (mParent != null) {
//通知父View,我现在是那个有焦点的View
mParent.requestChildFocus(this, this);
updateFocusedInCluster(oldFocus, direction);
}
//调用设置的View树全局焦点变化监听
if (mAttachInfo != null) {
mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
}
//调用自己的onFocusChangeListener方法
onFocusChanged(true, direction, previouslyFocusedRect);
refreshDrawableState();
}
}
方法中将mPrivateFlags中的表示是否有焦点的bit置为1,表示自己有焦点,这在上一章中分析过,之后调用父View的requestChildFocus的方法,如下:
@Override
public void requestChildFocus(View child, View focused) {
......
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变量,指向这个新的获得焦点的子View
mFocused = child;
}
if (mParent != null) {
//告诉父View,我是那个包含焦点View的乖儿子
mParent.requestChildFocus(this, focused);
}
父View的requestChildFocus方法中将mFocused成员变量指向这个有焦点的View,然后通知自己的父View我是那个包含焦点View的子View,如此遍历所有的父View,直到ViewRootImpl,这样就修改所有的父View中的mFocused变量了,之后有按键事件时就按这个路径传递KeyEvent,这也在上一篇中也有分析。
ViewGroup的requestFocus方法
ViewGroup复写了View的requestFocus(int direction, Rect previouslyFocusedRect)方法,如下:
@Override
public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
//获取ViewGroup相对于子View的获得焦点的顺序
int descendantFocusability = getDescendantFocusability();
boolean result;
switch (descendantFocusability) {
//拦截焦点,直接调用自己的获取焦点的逻辑
case FOCUS_BLOCK_DESCENDANTS:
result = super.requestFocus(direction, previouslyFocusedRect);
break;
//在子View之前,调用自己的获取焦点的逻辑,如果不能获得,遍历子View,让先子View处理
case FOCUS_BEFORE_DESCENDANTS: {
final boolean took = super.requestFocus(direction, previouslyFocusedRect);
result = took ? took : onRequestFocusInDescendants(direction,
previouslyFocusedRect);
break;
}
//在子view之后,先遍历子View,让子View处理,如果它们都不处理,则再自己处理
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;
}
在这个方法中ViewGroup根据自己相对子View获得焦点的顺序来确认调用方法的顺序。从代码中可以看出如果一个ViewGroup要获得焦点它的逻辑和View是一样的,而且由于ViewGroup默认设置了FOCUS_BEFORE_DESCENDANTS,如果它再设置focusable为true,它的想获得焦点的儿子们就不要指望爸爸主动给焦点了😂,只能通过自己的requestFocus去获得。
总结
简短总结一下本篇的内容:
- View的焦点模式可以使用focusable属性定义,也与clickable属性有关联
- ViewGroup在View的基础上定义了自己相对于子View的处理焦点的顺序
- View通过requestFocus方法获得焦点
- ViewGroup复写了requestFocus方法,加入了顺序判断
到这里按键事件的分发和获得焦点的过程分析完毕,但事情还没完,当按下按键时会发现焦点会在View之间移动,那按键事件是怎么转换为焦点View的变化的呢?请看下篇分析: Android TV开发按键与焦点深入分析(三)--按键事件转换成焦点移动的过程