ListView是我们常用的控件,基本每个项目天天写。 今天碰到一个现象,我的ListView布局是这样的:
发现点击其中的每一项没有反应,断点调试发现没有进入OnItemCLickListener中的onItemClick。
百度后发现博客园上有位园友也碰到这种情况,参考了http://www.cnblogs.com/livesoft/archive/2011/02/12/1951762.html
记录下来,做个小总结。
究竟是为什么呢?
查看了一下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中的onItemClick()方法了。