listView 不响应点击

在这里总结一下上面问题出现背景,item中有ImageButton,其余和平常使用listview一样的.当点击item时,onItemClickListener不起作用,ontouchListener中motionEvent.down消失了,事件只有点击item中的imagButton起作用。

    我们分析一下,当item出现了imageButton时,onItemClickListener不起作用,而在Touch中没有了down事件,首先说明onItemClickListener处理的和MotionEvent的down事件有关,然后问题的关键是这个down事件去了哪里呢?

    经过排查当item中有Checkable类以及Button类控件的时候,item的焦点会被子项获得,此时这些子控件会将焦点获取到,所以常常当点击item时变化的是子控件,item本身的点击没有响应。从而导致onItemClickListener不起作用。

    已经得知了问题导致的原因就是因为item没有获得焦点,焦点被子项拿走了,那么怎么解决这类问题?本人认为处理的途径无非就是通过设置子项不能获得焦点,同时item要获得焦点。  

    这里采用的方法,要用到两个属性:

一:

android:focusable="false"

这个属性的具体介绍可以i看我上一篇文章,设置的目的在于使得某个控件不能获得焦点。

二:

android:descendantFocusability="blocksDescendants"

这个属性用来设置子项焦点的处理先后顺序。

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.

android:beforeFocusability      viewgroup在子项处理之前获得焦点

android:afterFocusability            viewGroup在子项处理之后获得焦点

android:blocksFocusability          viewGroup阻止子项获得焦点

 

上面就是说子项焦点能力,定义了viewgroup和它的子元素处理的关系,这关系是指当一个view在获得焦点的时候,值必须是下面的常量之一。

       那么,我们肯定imageButton不能获得焦点,因此添加ImageButton属性 focusable="false",同时我们希望item中子项不能获得焦点,所以要把给android:descendantFocusability="blocksDescendants"属性添加到imageButton的父元素即可,简单的做可以设置item的根节点上。

猜你喜欢

转载自wenzongliang.iteye.com/blog/2206036