(原創)轉載請聲明出處http://www.cnblogs.com/linguanh/
問題原型:
ExpandableListView 展開失效。
--------------------直接看結論請拉置 紅線下-------------------
早在同年5月份的時候我寫過一篇 自定義 ExpandableListView 收縮類的 博文,那時候我還沒碰到這個問題,
一切很順利, 入口:http://www.cnblogs.com/linguanh/p/4521257.html


直到今天,本來想做個日程表,考慮到月份是可選的,所以想重新使用 ExpandableListView,逐使用之。我們知道使用 ExpandableListView 要為它配置個 數據是配置器,也就是ExpandableListAdapter,它有9個接口函數要求重寫,具體請轉至我的的專題介紹了解它:http://www.cnblogs.com/linguanh/p/4521257.html
其中有一個是:
1 @Override 2 public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
它的作用是讓我們返回一級目錄的 view,通常使用五大布局中的一種,例如:
LinearLayout Group =(LinearLayout) RelativeLayout.inflate(上下文, R.layout.布局, null);
我們就在 getGroupView 函數中返回這個view,注意:里面 R.layout.布局 就是我們的自定義一級目錄 xml 布局
文件,也是我要說的坑所在。
我在確定編碼沒問題之后,就點運行了,幾秒后, getGroupView 加載的一級目錄 xml 布局顯示出來了,OK,很好,然后我就點擊了,點了之后發現,妹的,沒展開二級目錄。然后就屁顛屁顛地回去找bug,代碼確定沒錯,於是加入了很多log,再次運行,查看日志。我勒個去!
1 @Override 2 public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
這貨居然沒被執行,里面的log 沒打印出。於是下意識地去查看我在getChildView引入的 xml 布局,我上面說的第一個 xml 布局是一級目錄的,在getChildView 是二級目錄的 布局。查看之后,實在找不出它有錯的理由,於是乎,就找之前成功過的例子 xml 文件替換進去,運行,點擊,還是不行,當時我就fuck 了 dog 了。
然后轉至 getGroupView 一級目錄 xml布局的引入函數,查看仍找不出錯的理由,同上,用之前成功過的替換下,運行,點擊,made,居然行了。然后我就開始 把原來不行的 布局文件 和 替換后可以的來對比。
控件類型對比差異:不行的布局文件帶有 button 控件,可以的沒有帶有button,其它地方一樣。
看到這,突然覺得,是不是 button 的點擊屬性覆蓋了原本的一級目錄可點擊屬性?再看看 button 的寬和高,即
它的有效點擊范圍,都是 wrap,按道理沒占滿整個父view,我點其他地方,不就是沒點到它嗎。
可事實就是如此。button 的存在導致 ExpandableListView 一級目錄可點擊性失效。
這真是天坑,馬上百度百度,看看有沒有相同案例,百度了才發現,有碰到和我相同問題的,但是都沒有解決!!!
心情有點小激動,哈哈。
---------------------------------------------------------
總結:
ExpandableListView 的 數據適配器 ExpandableListAdapter 中的 getGroupView 函數中所引入的自定義一級目錄 xml 布局文件不能帶有 button,否則會導致展開失效,ImageButton沒嘗試過,不過可能也是不行的。
舉例對比:
反例,帶有button的
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="horizontal" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent"> 6 7 <ImageView 8 android:layout_marginLeft="@dimen/extend_x_left" 9 android:id="@+id/entend_x" 10 android:background="@drawable/extend_x" 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" /> 13 <TextView 14 android:alpha="0.8" 15 android:id="@+id/time_coustom" 16 android:layout_marginLeft="20dp" 17 android:text="1:00pm" 18 android:textSize="17dp" 19 android:layout_width="wrap_content" 20 android:layout_height="wrap_content" 21 /> 22 <Button 23 android:id="@+id/down" 24 android:layout_marginTop="10dp" 25 android:layout_marginRight="10dp" 26 android:background="@drawable/right" 27 android:layout_width="15dp" 28 android:layout_height="15dp" /> 29 </LinearLayout>
可行的:
上面的 代碼去掉 button
