開發中很常見的一個問題,項目中的listview或者GridView 不僅僅是簡單的文字,常常需要自己定義item,自己的Adapter去繼承BaseAdapter,在adapter中按照需求進行編寫,問題就出現了,可能會發生點擊每一個item的時候沒有反應,無法獲取的焦點。原因多半是由於在你自己定義的Item中存在諸如ImageButton,Button,CheckBox等子控件(也可以說是Button或者Checkable的子類控件),此時這些子控件會將焦點獲取到,所以常常當點擊item時變化的是子控件,item本身的點擊沒有響應。
例如:
這時候就可以使用descendantFocusability來解決啦,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會覆蓋子類控件而直接獲得焦點
通常我們用到的是第三種,即在Item佈局的根佈局加上android:descendantFocusability=”blocksDescendants”的屬性
還有 記得 在點擊的控件裏面加上
android:clickable="false"
android:focusable="false"
Item的代碼爲:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bind_border"
android:descendantFocusability="blocksDescendants"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<com.customWidget.RoundedCornerImageView
android:id="@+id/product_item_product_icom"
android:layout_width="120dp"
android:layout_height="140dp"
android:scaleType="fitXY"
android:src="@drawable/demoproduct" />
<ImageButton
android:id="@+id/product_del_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/login_close_button"
android:clickable="false"
android:focusable="false" />
</LinearLayout>
<TextView
android:id="@+id/tv_name"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="關節回覆基本準則"
android:textStyle="normal|italic" />
<TextView
android:id="@+id/btn_cart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/mybutton"
android:focusable="false"
android:padding="8dp"
android:text="放入購物車" />
</LinearLayout>
Ok啦