Android ListView不响应OnItemClickListener解决办法
有時(shí)候,當(dāng)ListView中的每一個(gè)item是自定義的View時(shí),有可能會(huì)導(dǎo)致ListView的OnItemClickListener的listener無法調(diào)用,請(qǐng)看如下情況:
如果你的自定義ListViewItem中有Button或者Checkable的子類控件的話,那么默認(rèn)focus是交給了子控件,而 ListView的Item能被選中的基礎(chǔ)是它能獲取Focus,也就是說我們可以通過將ListView中Item中包含的所有控件的 focusable屬性設(shè)置為false,這樣的話ListView的Item自動(dòng)獲得了Focus的權(quán)限,也就可以被選中了。
我們可以通過對(duì)Item Layout的根控件設(shè)置其android:descendantFocusability="blocksDescendants"即可,這樣Item Layout就屏蔽了所有子控件獲取Focus的權(quán)限,不需要針對(duì)Item Layout中的每一個(gè)控件重新設(shè)置focusable屬性了,如此就可以順利的響應(yīng)onItemClickListener中的onItemClick()方法了。
總結(jié):?
原因:
ListView中的Item內(nèi)部的View獲得了焦點(diǎn),如Button, Checkbox等。?
解決辦法:?
不要讓ListView中的Item內(nèi)部的View獲得焦點(diǎn)就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. |
?
注意:
還有一種情況也會(huì)導(dǎo)致OnItemClickListener或OnItemLongClickListener回調(diào)不會(huì)執(zhí)行,那就是ListView的child設(shè)置了onClickListener或onLongClickListener。我們可以通過源代碼看出,在你調(diào)用setOnClickListener()方法后,它會(huì)調(diào)用setClickable(true),在onTouchEvent里面的實(shí)現(xiàn)如下:?
?
[java]?view plain?copy?
當(dāng)一個(gè)View在onTouchEvent里面返回true后,ListView就不會(huì)正常接收到事件。
轉(zhuǎn)載于:https://www.cnblogs.com/exmyth/p/5387153.html
總結(jié)
以上是生活随笔為你收集整理的Android ListView不响应OnItemClickListener解决办法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt 【widget如何铺满窗口】
- 下一篇: android sina oauth2.