Sometimes, when each item in the ListView is a custom view, it is possible that the Onitemclicklistener listener of the ListView cannot be called, see the following:
If your custom ListViewItem has a button or checkable child control, then the default focus is given to the child control, and the ListView item can be selected based on its ability to get focus, This means that we can set the Focusable property of all controls contained in the ListView to False, so that the ListView item automatically gets the focus permission and can be selected.
We can do this by setting its android:descendantfocusability= "Blocksdescendants" on the root control of item layout, so that the item Layout blocks all child controls from getting focus and does not need to reset the Focusable property for each control in item layout, so it can respond smoothly to Onitemclick () in Onitemclicklistener Method.
Summary:
Reason:
The view inside the item in the ListView gets the focus, such as a button, a checkbox, and so on.
Workaround:
Do not let the item inside the ListView get the focus on it OK, do this:android:descendantfocusability= "Blocksdescendants"
public static final int descendantfocusability
Defines the relationship between the ViewGroup and its descendants when looking-a View to take focus.
| Constant |
Value |
Description |
| Beforedescendants |
0 |
The ViewGroup'll get focus before any of its descendants. |
| Afterdescendants |
1 |
The ViewGroup would get focus only if none of its descendants want it. |
| Blocksdescendants |
2 |
The ViewGroup would block its descendants from receiving focus. |
Attention:
There is also a situation that causes the Onitemclicklistener or Onitemlongclicklistener callback to not execute, That is, the child of the ListView sets the Onclicklistener or Onlongclicklistener. We can see through the source code that, after you call the Setonclicklistener () method, it calls Setclickable (true), and the implementation in Ontouchevent is as follows:
[Java]View Plaincopy
- if (((viewflags & clickable) = = Clickable | |
- (ViewFlags & long_clickable) = = long_clickable)) {
- // ....
- return true;
- }
When a view returns true in Ontouchevent, the ListView does not receive the event normally.
Android ListView does not respond to Onitemclicklistener workaround