Android ListView不响应OnItemClickListener解决办法
有時候,當ListView中的每一個item是自定義的View時,有可能會導致ListView的OnItemClickListener的listener無法調用,請看如下情況:
如果你的自定義ListViewItem中有Button或者Checkable的子類控件的話,那么默認focus是交給了子控件,而 ListView的Item能被選中的基礎是它能獲取Focus,也就是說我們可以通過將ListView中Item中包含的所有控件的 focusable屬性設置為false,這樣的話ListView的Item自動獲得了Focus的權限,也就可以被選中了。
我們可以通過對Item Layout的根控件設置其android:descendantFocusability="blocksDescendants"即可,這樣Item Layout就屏蔽了所有子控件獲取Focus的權限,不需要針對Item Layout中的每一個控件重新設置focusable屬性了,如此就可以順利的響應onItemClickListener中的onItemClick()方法了。
總結:?
原因:
ListView中的Item內部的View獲得了焦點,如Button, Checkbox等。?
解決辦法:?
不要讓ListView中的Item內部的View獲得焦點就OK了,這樣做:android:descendantFocusability="blocksDescendants"
public static final int descendantFocusability
Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.
?
| 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. |
?
注意:
還有一種情況也會導致OnItemClickListener或OnItemLongClickListener回調不會執行,那就是ListView的child設置了onClickListener或onLongClickListener。我們可以通過源代碼看出,在你調用setOnClickListener()方法后,它會調用setClickable(true),在onTouchEvent里面的實現如下:?
?
[java]?view plain?copy?
當一個View在onTouchEvent里面返回true后,ListView就不會正常接收到事件。
轉載于:https://www.cnblogs.com/exmyth/p/5387153.html
總結
以上是生活随笔為你收集整理的Android ListView不响应OnItemClickListener解决办法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt 【widget如何铺满窗口】
- 下一篇: Springmvc整合mybatis