Android開發(fā)中,經(jīng)常需要為L(zhǎng)istView定制Adapter,綁定各種子類控件。
如果Item包含Button等Checkable的控件,那么就會(huì)發(fā)生點(diǎn)擊Item無法響應(yīng)的問題。原因是自己定義的Item中Button等Checkable控件先獲取到了焦點(diǎn)。
解決方案有兩種:
-
在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.
該屬性定義了當(dāng)View獲取焦點(diǎn)時(shí),viewGroup與子控件的關(guān)系:
beforeDescendants:viewgroup
會(huì)優(yōu)先子類控件而獲取到焦點(diǎn)
afterDescendants:viewgroup
當(dāng)子類控件不需要獲取焦點(diǎn)時(shí)才獲取焦點(diǎn)
blocksDescendants:viewgroup
會(huì)覆蓋子類控件而直接獲得焦點(diǎn)
(測(cè)試第三個(gè)可以,第一個(gè)沒反應(yīng)。。。) 在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>