溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android自定義ListView單擊事件失效的解決方法

發(fā)布時間:2020-09-02 20:41:29 來源:腳本之家 閱讀:186 作者:_York 欄目:移動開發(fā)

因為自帶的listView不能滿足項目需求,通過實現(xiàn)自己的Adapter去繼承ArrayAdapter 來實現(xiàn)自定義ListView的Item項目。

出現(xiàn)點擊ListView的每一項都不會執(zhí)行setOnItemClickListener 里面的onItemClick 方法。

原因是item里面存在一些子控件,默認點擊獲取的焦點跑去子控件去了,點擊失效。

解決辦法:

在item的根目錄加入android: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>

該屬性是當一個為view獲取焦點時,定義viewGroup和其子控件兩者之間的關(guān)系。

屬性的值有三種:

  •         beforeDescendants:viewgroup會優(yōu)先其子類控件而獲取到焦點
  •         afterDescendants:viewgroup只有當其子類控件不需要獲取焦點時才獲取焦點
  •         blocksDescendants:viewgroup會覆蓋子類控件而直接獲得焦點

我們使用blocksDescendants 屬性來覆蓋子類控件,而直接獲取焦點。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI