ListView的Item不響應OnItemClick
開發中我們會經常用到ListView,絕大多時候我們都會自定義Item,假如我們自定義的Item中存在Image Button,Button,CheckBox,RatingBar等時,我們會發現加入我們這時候為ListView設定setOnItemClickListener,然後點選Item,我們會發現—-什麼也不會發生!!!
why?
原因很簡單,我們的Button等等把點選事件攔截了,舉個例子,Item布局為LinearLayout中有個Button,當我們點選Item的時候,Andriod處理事件是先捕獲再冒泡,LinearLayout捕獲了這個事件,然後向内傳遞給Button,Button也捕獲到了,注意:開始冒泡了,此時Button響應了這個事件,然後他又把這個事件攔截了,是以這個事件根本傳遞不到Linearlayout那裡
解決辦法
我們隻需要在Item的根布局處添加
android:descendantFocusability="blocksDescendants"
就可以搞定了
分析
descendantFocusability從字面上看意思就是子孫的獲得焦點的能力,也就是子控件獲得焦點的能力,它有三個屬性可以選擇
Item | 翻譯 | 原文 |
---|---|---|
beforeDescendants | viewgroup會優先其子類控件而擷取到焦點 | The ViewGroup will get focus before any of its descendants |
afterDescendants | viewgroup隻有當其子類控件不需要擷取焦點時才擷取焦點 | The ViewGroup will get focus only if none of its descendants want it |
blocksDescendants | viewgroup會覆寫子類控件而直接獲得焦點 | The ViewGroup will block its descendants from receiving focus |
blocksDescendants的英文原文看到:ViewGroup會阻塞(注意不是阻止,這個很重要)它的子控件拿到foucs 意思就是,爸爸先來