经常会碰到ListView Item和子控件焦点冲突问题,查了很多资料后发现问题出在listview item的父容器布局中 android:descendantFocusability属性和子控件 android:focus属性的冲突
android:descendantFocusability属性共有三个取值,分别为
beforeDescendants:viewgroup会优先其子类控件而获取到焦点
afterDescendants:viewgroup 只有当其子类控件不需要获取焦点时才获取焦点
blocksDescendants:viewgroup 会覆盖子类控件而直接获得焦点
下面我用列表形式展示设置不同属性的结果:
android:descendantFocusability="blocksDescendants":
focusable item可点击性 子控件(Button等)可点击性
false true true
true true true
android:descendantFocusability="afterDescendants":
false true true
true false true
android:descendantFocusability="beforeDescendants":false true true
true false true
由此可见,当listview有子控件存在时,子控件获取焦点的优先级要高于listview item本身,参考上表结果,如果想要listview item 无法点击,只相应子控件点击事件可设置父容器android:descendantFocusability="afterDescendants"或者android:descendantFocusability="beforeDescendants":并设置子控件android:focusable="true"。除此之外分别对父容器和子控件的上述属性对应设置即可实现不同效果。