SoFunction
Updated on 2025-04-07

Solution to Button's focus in Listview

The solution to preempt focus is:

Item xml root node adds android:descendantFocusability="blocksDescendants"

Button Settings

android:focusable="false"

In this way, click Button and ListView Item can respond to their own click events separately

A very common problem in development. The listview in a project is not just simple text. It often requires you to define the listview yourself. Your own Adapter inherits the BaseAdapter and writes it according to the needs in the adapter. The problem arises. There may be no response and the focus cannot be obtained when clicking on each item.

The reason is mostly because there are sub-controls such as ImageButton, Button, CheckBox, etc. in the Item you define yourself (or sub-class controls of Button or Checkable). At this time, these sub-controls will get the focus, so often when clicking on the item, the sub-control changes, and the click of the item itself does not respond.

At this time, you can use descendantFocusability to solve the problem.

This property defines the relationship between the viewGroup and its child controls when a view gets focus.

There are three types of attribute values:

beforeDescendants: viewgroup will prioritize its subclass controls to get focus

afterDescendants: viewgroup only gets focus when its subclass control does not need to get focus

blocksDescendants: viewgroup will override subclass controls and directly get focus

Usually we use the third type, that is, add the attribute **android:descendantFocusability="blocksDescendants" to the root layout of the Item layout. At this point, the supernatural event clicked on the listview has come to an end.

The above is the solution to Button's focus in Listview introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!