Android ViewGroup.setDescendantFocusability函數

這個函數是在ViewGroup裏定義的,主要用於控制child View獲取焦點的能力,比如是否阻止child View獲取焦點。

 

他有三個常量可供設置

 

  1. FOCUS_BEFORE_DESCENDANTS ViewGroup本身先對焦點進行處理,如果沒有處理則分發給child View進行處理
  2. FOCUS_AFTER_DESCENDANTS 先分發給Child View進行處理,如果所有的Child View都沒有處理,則自己再處理
  3. FOCUS_BLOCK_DESCENDANTS ViewGroup本身進行處理,不管是否處理成功,都不會分發給ChildView進行處理

我們看下這個方法的實現
Setdescendantfocusability(int focusability)代碼  收藏代碼
  1. public void setDescendantFocusability(int focusability) {  
  2.         switch (focusability) {  
  3.             case FOCUS_BEFORE_DESCENDANTS:  
  4.             case FOCUS_AFTER_DESCENDANTS:  
  5.             case FOCUS_BLOCK_DESCENDANTS:  
  6.                 break;  
  7.             default:  
  8.                 throw new IllegalArgumentException("must be one of FOCUS_BEFORE_DESCENDANTS, "  
  9.                         + "FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS");  
  10.         }  
  11.         mGroupFlags &= ~FLAG_MASK_FOCUSABILITY;  
  12.         mGroupFlags |= (focusability & FLAG_MASK_FOCUSABILITY);  
  13.     }  
 

 

可以看到,只有這三個常量可以設置,不是這三個常量會拋出異常的。

 

 

設置後,會在requestFocus(int direction, Rect previouslyFocusedRect) 方法里根據設置進行相應的處理。來看下實現

 

Requestfocus(int direction, rect previouslyfocusedrect)代碼  收藏代碼
  1. public boolean requestFocus(int direction, Rect previouslyFocusedRect) {  
  2.         if (DBG) {  
  3.             System.out.println(this + " ViewGroup.requestFocus direction="  
  4.                     + direction);  
  5.         }  
  6.         int descendantFocusability = getDescendantFocusability();  
  7.   
  8.         switch (descendantFocusability) {  
  9.             case FOCUS_BLOCK_DESCENDANTS:  
  10.                 return super.requestFocus(direction, previouslyFocusedRect);  
  11.             case FOCUS_BEFORE_DESCENDANTS: {  
  12.                 final boolean took = super.requestFocus(direction, previouslyFocusedRect);  
  13.                 return took ? took : onRequestFocusInDescendants(direction, previouslyFocusedRect);  
  14.             }  
  15.             case FOCUS_AFTER_DESCENDANTS: {  
  16.                 final boolean took = onRequestFocusInDescendants(direction, previouslyFocusedRect);  
  17.                 return took ? took : super.requestFocus(direction, previouslyFocusedRect);  
  18.             }  
  19.             default:  
  20.                 throw new IllegalStateException("descendant focusability must be "  
  21.                         + "one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS "  
  22.                         + "but is " + descendantFocusability);  
  23.         }  
  24.     }  

 

通過這裏的實現可以看到上面定義的三個常量設置的意思。。

發佈了45 篇原創文章 · 獲贊 3 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章