ListView focus problem


Introduction to this section

If you add Button, CheckBox, EditText and other controls to the Item of ListView, you may need to consider To a problem: a focus problem of ListView! In this section we will learn several ways to solve this problem!

We can write a simple listView with a Button, CheckBox, and EditText, but when we click, we find that The ListView item cannot be clicked, the onItemClick method cannot be triggered, and the onItemLongClick method cannot be triggered. This is a focus issue of ListView! It means that the focus of ListView is snatched by other controls. Let's see how solve this problem?


Method 1: Set: android:focusable="false" for the component that has preempted the control Control setting

android:focusable="false"
can solve this problem Or call after getting the control in the code:

setFocusable(false)!! In addition, EditText does not work. If we set android:focusable="false", this B can get focus but all of a sudden The focus is lost again, and the small keyboard will not pop up. I don’t know how to solve it yet. I heard others say it is a bug in ListView. If If you know the solution, please let me know, thank you~

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

As the title says, in Item Just add the above attribute to the root node of the layout,

android:descendantFocusability="blocksDescendants"
. In addition, this attribute has three optional values:

beforeDescendants
    : viewgroup will give priority to its subclass controls and obtain focus
  • afterDescendants
  • : viewgroup will only obtain focus when its subclass controls do not need to obtain focus
  • blocksDescendants
  • : viewgroup will overwrite subclass controls and directly gain focus
Summary of this section:

Okay, the above is the solution Two methods for ListView focus problem, very simple, if there is anything about EditText Solutions to focus issues are welcome, thank you~