Solution to Android Custom ListView Click Event Failure

  • 2021-09-20 21:26:02
  • OfStack

Because the self-contained listView can not meet the project requirements, the Item project of customizing ListView can be realized by implementing its own Adapter to inherit ArrayAdapter.

Every item that clicks ListView will not execute the onItemClick method in setOnItemClickListener.

The reason is that there are 1 child controls in item, and the focus obtained by default clicks goes to the child controls, and clicks fail.

Solution:

Add android to the root of item: descendantFocusability= "blocksDescendants"


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:descendantFocusability="blocksDescendants">

  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:padding="5dp">


    <ImageView
      android:id="@+id/imageView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:srcCompat="@drawable/message_oc" />

    <TextView
      android:id="@+id/textTitle"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="title"
      android:textSize="25dp"
      android:layout_marginLeft="15dp"/>

    <TextView
      android:id="@+id/textDate"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:gravity="right"
      android:text="date" />
  </LinearLayout>

  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView
      android:id="@+id/textMessage"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:ems="10"
      android:inputType="textMultiLine"
      android:text="message"
      android:textSize="20dp"/>
  </LinearLayout>

</LinearLayout>

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

Property has three values:

beforeDescendants: viewgroup gets focus over its subclass controls afterDescendants: viewgroup gets focus only if its subclass controls do not need to get focus blocksDescendants: viewgroup overrides subclass controls to get focus directly

We use the blocksDescendants property to override the subclass control and get the focus directly.


Related articles: