[轉載]解決ListView的OnItemClickListener無效問題

原作地址:http://www.jianshu.com/p/db56284c7878

當我們自定義ListView的item時,常常會加入諸如Button,ImageButton,CheckBox等控件,這時候我們會發現:ListView.setOnItemClickListener(new ...)沒有效果,點擊Item沒有反應,那是因爲此時的焦點已經被子view獲取(Button,ImageButton...),所以響應點擊操作的並不是Item。

解決方案:

  • descendantFocusability

    API描述如下:
    android:descendantFocusability
    Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.
    Must be one of the following constant values.


該屬性是當一個爲view獲取焦點時,定義viewGroup和其子控件兩者之間的關係。
屬性的值有三種:

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

通常我們用到的是blocksDescendants,在Item的根佈局設置
android:descendantFocusability="blocksDescendants"

  • item_list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
------------------------------------------------------------------------------
    android:descendantFocusability="blocksDescendants"
------------------------------------------------------------------------------
>
    <ImageView
        android:id="@+id/image_library"
        android:layout_width="match_parent"
        android:layout_height="140dp"
        android:background="@drawable/color_white_yellow"/>
    <TextView
        android:id="@+id/text_library"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="大衆書局"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_marginTop="10dp"
        android:textColor="@color/white"/>
    <TextView
        android:id="@+id/text_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text_library"
        android:text="東城匯 | 仙林"
        android:layout_centerHorizontal="true"
        android:textSize="15sp"
        android:textColor="@color/white"/>

    <ImageButton
        android:id="@+id/btn_star"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_margin="10dp"/>

</RelativeLayout>

ok,設置好了之後,子view的可以設置OnClick(),Item也可以setOnItemClickListener()了,又可以愉快的玩耍了。



作者:AlphaRay
鏈接:http://www.jianshu.com/p/db56284c7878
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章