在Android軟件設計與實現中我們通常都會使用到ListView這個控件,系統有一些預置的Adapter可以使用,例如SimpleAdapter和ArrayAdapter,但是總是會有一些情況我們需要通過自定義ListView來實現一些效果,那么在這個時候,我們通常會碰到自定義ListView無法選中整個ListViewItem的情況,也就是無法響應ListView的onItemClickListener中的onItemClick()方法,之后自己查看了一下ViewGroup的源碼,發現了以下的一段常量聲明:
* This view will get focus before any of its descendants.
*/
public static final int FOCUS_BEFORE_DESCENDANTS = 0× 20000;
/* *
* This view will get focus only if none of its descendants want it.
*/
public static final int FOCUS_AFTER_DESCENDANTS = 0× 40000;
/* *
* This view will block any of its descendants from getting focus, even
* if they are focusable.
*/
public static final int FOCUS_BLOCK_DESCENDANTS = 0× 60000;
/* * * This view will get focus before any of its descendants. */
public static final int FOCUS_BEFORE_DESCENDANTS = 0× 20000;
/* * * This view will get focus only if none of its descendants want it. */
public static final int FOCUS_AFTER_DESCENDANTS = 0× 40000;
/* * * This view will block any of its descendants from getting focus, even * if they are focusable. */
public static final int FOCUS_BLOCK_DESCENDANTS = 0× 60000;
我們看到了一行代碼定義的變量的意思是“當前View將屏蔽他所有子控件的Focus狀態,即便這些子控件是可以Focus的”,其實這段話的意思就是這個變量代表着當前的View將不顧其子控件是否可以Focus自身接管了所有的Focus,通常默認能獲得focus的控件有Button,Checkable繼承來的所有控件,這就意味着如果你的自定義ListViewItem中有Button或者Checkable的子類控件的話,那么默認focus是交給了子控件,而ListView的Item能被選中的基礎是它能獲取Focus,也就是說我們可以通過將ListView中Item中包含的所有控件的focusable屬性設置為false,這樣的話ListView的Item自動獲得了Focus的權限,也就可以被選中了,也就會響應onItemClickListener中的onItemClick()方法,然而將ListView的Item Layout的子控件focusable屬性設置為false有點繁瑣,我們可以通過對Item Layout的根控件設置其android:descendantFocusability=”blocksDescendants”即可,這樣Item Layout就屏蔽了所有子控件獲取Focus的權限,不需要針對Item Layout中的每一個控件重新設置focusable屬性了,如此就可以順利的響應onItemClickListener中的onItenClick()方法了。例如我的ListViw的每個item項是RelativeLayout,那么我就可以設置RelativeLayout的android:descendantFocusability=”blocksDescendants”即可。注意:這個屬性不能設置給ListView,設置了也不起作用。
最近做的項目中用到ImageSwitcher 來顯示多張圖片,最近想在ImageSwitcher中點擊不同的圖片,通過一個activity來顯示不同的內容,當是第一想法是通過設置imageswitcher的setOnClickListener事件,但是設置斷點后一直跟不進去.最后看api,可以設置android:descendantFocusability="blocksDescendants",