這個函數是在ViewGroup裏定義的,主要用於控制child View獲取焦點的能力,比如是否阻止child View獲取焦點。
他有三個常量可供設置
- FOCUS_BEFORE_DESCENDANTS ViewGroup本身先對焦點進行處理,如果沒有處理則分發給child View進行處理
- FOCUS_AFTER_DESCENDANTS 先分發給Child View進行處理,如果所有的Child View都沒有處理,則自己再處理
- FOCUS_BLOCK_DESCENDANTS ViewGroup本身進行處理,不管是否處理成功,都不會分發給ChildView進行處理
- 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);
- }
可以看到,只有這三個常量可以設置,不是這三個常量會拋出異常的。
設置後,會在requestFocus(int direction, Rect previouslyFocusedRect) 方法里根據設置進行相應的處理。來看下實現
- public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
- if (DBG) {
- System.out.println(this + " ViewGroup.requestFocus direction="
- + direction);
- }
- int descendantFocusability = getDescendantFocusability();
- switch (descendantFocusability) {
- case FOCUS_BLOCK_DESCENDANTS:
- return super.requestFocus(direction, previouslyFocusedRect);
- case FOCUS_BEFORE_DESCENDANTS: {
- final boolean took = super.requestFocus(direction, previouslyFocusedRect);
- return took ? took : onRequestFocusInDescendants(direction, previouslyFocusedRect);
- }
- case FOCUS_AFTER_DESCENDANTS: {
- final boolean took = onRequestFocusInDescendants(direction, previouslyFocusedRect);
- return took ? took : super.requestFocus(direction, previouslyFocusedRect);
- }
- default:
- throw new IllegalStateException("descendant focusability must be "
- + "one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS "
- + "but is " + descendantFocusability);
- }
- }
通過這裏的實現可以看到上面定義的三個常量設置的意思。。