1. 程式人生 > >ListView中Item與Checkable子類控件搶焦點問題

ListView中Item與Checkable子類控件搶焦點問題

.com 控件 schema android開發 red 定制 xmlns @+ div

Android開發中,經常需要為ListView定制Adapter,綁定各種子類控件。
如果Item包含Button等Checkable的控件,那麽就會發生點擊Item無法響應的問題。原因是自己定義的Item中Button等Checkable控件先獲取到了焦點。

解決方案有兩種:

1.在ListView的Item的xml文件的根元素如LinearLayout中添加屬性

android:descendantFocusability="blocksDescendants"
該屬性定義了當View獲取焦點時,viewGroup與子控件的關系:
beforeDescendants:viewgroup
會優先子類控件而獲取到焦點
afterDescendants:viewgroup當子類控件不需要獲取焦點時才獲取焦點
blocksDescendants:viewgroup會覆蓋子類控件而直接獲得焦點
(測試第三個可以,第一個沒反應。。。)
2.在Checkable控件中添加屬性:
android:focusable="false"
android:clickable="true"
添加位置
 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2  android:id="@+id/linearLayout
" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="horizontal" 6 android:descendantFocusability="blocksDescendants" > 7 <Button android:id="@+id/button" 8 android:layout_width="50dp" 9 android:layout_height="100dp" 10 android:focusable="
false" 11 android:clickable="true" 12 android:text="按鈕"/> 13 <TextView 14 android:id="@+id/textView" 15 android:layout_width="50dp" 16 android:layout_height="100dp" 17 android:focusable="false" 18 android:clickable="true" 19 android:text="文本" /> 20 </LinearLayout>

ListView中Item與Checkable子類控件搶焦點問題