當我們自定義ListView的item時,常常會加入諸如Button型宝,ImageButton八匠,CheckBox等控件,這時候我們會發(fā)現:ListView.setOnItemClickListener(new ...)沒有效果趴酣,點擊Item沒有反應梨树,那是因為此時的焦點已經被子view獲取(Button,ImageButton...),所以響應點擊操作的并不是Item岖寞。
解決方案:
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會優(yōu)先其子類控件而獲取到焦點
- 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()了隶垮,又可以愉快的玩耍了藻雪。
疑問?
從字面意義理解狸吞,[beforeDescendants]也應該是可以的勉耀,但是我設置了之后沒效果,如果你知道蹋偏,求指點便斥。