Introduction to This Section

If you add controls such as Button, CheckBox, EditText to the ListView's Item, you may need to consider a problem: a focus problem with ListView! In this section, we will learn a few methods to solve this problem!

We can write a simple ListView with a Button, CheckBox, and EditText on it, but when we click, we find that the ListView items cannot be clicked, and neither the onItemClick method nor the onItemLongClick method is triggered. This is a focus problem with ListView! That is, the focus of ListView has been stolen by other controls. Let's see how to solve this problem below.


Method 1: Set android:focusable="false" for the components that have stolen focus

As stated in the title, just set it for the controls that have stolen the ListView Item focusandroid:focusable="false"and the problem will be solved. Or after obtaining the control in code, call:setFocusable(false)!! In addition, EditText won't work with this. If we set android:focusable="false", this thing can gain focus but then loses it immediately, and it won't pop up the small keyboard either. I don't currently know how to solve it. I've heard it's a bug of ListView. If anyone knows the solution, please let us know. Thanks~


Method 2: Set android:descendantFocusability="blocksDescendants" on the item root node

As stated in the title, add the above attribute to the root node of the Item layout,android:descendantFocusability="blocksDescendants"and that's it. Additionally, this attribute has three selectable values:

  • beforeDescendantsbeforeDescendants: The viewgroup will prioritize obtaining focus over its child controls
  • afterDescendantsafterDescendants: The viewgroup only obtains focus when its child controls do not need focus
  • blocksDescendantsblocksDescendants: The viewgroup will override child controls and directly obtain focus

Summary of This Section:

Alright, the above are two methods for solving the ListView focus problem. They are very simple. If you have a solution for the EditText focus problem, feel free to share it. Thanks~