Android ListView item 焦点被抢无法点击

 Android ListView item 焦点被抢无法点击

  通常,我们会自定义 ListView Item 的 Layout,当自定义的 Item Layout 含有主动获得焦点的控件时(例如 Button, ImageButton 等),那么我们就没办法点击 ListView Item 自己的点击事件。

解决办法很简单,只要在Item Layout 的根布局中加上 android:descendantFocusability = "blocksDescendants" 属性即可。如下方的 Item 布局文件所示:

Java

这里再说说 descendantFocusability 这个属性的作用。

根据 官方说明 ,descendantFocusability 定义了 ViewGroup 和子控件的在获取焦点时的关系。

有下面三种取值:

  • beforeDescendants,ViewGroup 会在所有子控件之前获得焦点
  • afterDescendants,ViewGroup 会在所有子控件都不需要焦点时获得焦点
  • blocksDescendants,ViewGroup会阻断子控件获得焦点。

通常,我们只要把 descendantFocusability 设置为 blocksDescendants,即可解决由于 Item 里的 Button 抢夺焦点导致 Item 本身无法点击的问题。

猜你喜欢

转载自yangguangfu.iteye.com/blog/2247069