Android開發(fā)中,經常需要為ListView定制Adapter,綁定各種子類控件。
如果Item包含Button等Checkable的控件,那么就會發(fā)生點擊Item無法響應的問題。原因是自己定義的Item中Button等Checkable控件先獲取到了焦點。
解決方案有兩種:
-
在ListView的Item的xml文件的根元素如LinearLayout中添加屬性
android:descendantFocusability="blocksDescendants"
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
會覆蓋子類控件而直接獲得焦點
(測試第三個可以,第一個沒反應。。。) 在Checkable控件中添加屬性:
android:focusable="false"
android:clickable="true"
添加位置
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants" >
<Button android:id="@+id/button"
android:layout_width="50dp"
android:layout_height="100dp"
android:focusable="false"
android:clickable="true"
android:text="按鈕"/>
<TextView
android:id="@+id/textView"
android:layout_width="50dp"
android:layout_height="100dp"
android:focusable="false"
android:clickable="true"
android:text="文本" />
</LinearLayout>