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

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

解決方案有兩種:

  1. 在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會優先子類控件而獲取到焦點
    afterDescendants:viewgroup當子類控件不需要獲取焦點時才獲取焦點
    blocksDescendants:viewgroup會覆蓋子類控件而直接獲得焦點
    (測試第三個可以,第一個沒反應。。。)

  2. 在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>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容