之前在项目中遇到了一个问题,就是一个ListView,我在Item中设置了Button,类似下图的样子(这里只是个例子)
“编辑”和“删除”都能点击,但是当我设置了onItemClickListener后,点击Item却没有了反应。
查了一些资料,最后了解到,在Item的xml文件中最外层的View上加上如下属性:
android:descendantFocusability="blocksDescendants"
onItemClickListener就能使用了。看来这是一个获取焦点的问题,Item失效的原因就是无法获取焦点。
上了Android官网查看,发现该属性在ViewGroup类中就有了
点进去看详细信息:
android:descendantFocusability
Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.
Must be one of the following constant values.
Constant | Value | Description |
---|---|---|
beforeDescendants | 0 | The ViewGroup will get focus before any of its descendants. |
afterDescendants | 1 | The ViewGroup will get focus only if none of its descendants want it. |
blocksDescendants | 2 | The ViewGroup will block its descendants from receiving focus. |
This corresponds to the global attribute resource symbol descendantFocusability
.
after就是当所有子View都不要焦点时ViewGroup才会得到焦点
blocks就是ViewGroup会阻碍它的子View获取焦点
三种方法,大家可以选择适合自己代码口味的.......