bug重現(xiàn):通過mListView.setOnItemClickListener設(shè)置item點(diǎn)擊事件,正常情況下沒有問題,但當(dāng)item里面嵌套了搶焦點(diǎn)的控件(比如 Button ,CheckBox等),那么點(diǎn)擊item的時(shí)候,Button等搶焦點(diǎn)的控件會(huì)搶先反應(yīng),就會(huì)導(dǎo)致點(diǎn)擊item時(shí)沒有反應(yīng)。
解決辦法:想要item有自己的焦點(diǎn),Button等控件有自己的焦點(diǎn)的話,需要在item的根控件里面設(shè)置android:descendantFocusability="blocksDescendants",這個(gè)屬性值表示子有子的焦點(diǎn),父有父的焦點(diǎn)。
java代碼
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "onItemClick: ------");
}
});
item布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal">
<!--標(biāo)題-->
<TextView
android:id="@+id/tv_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"
android:text="標(biāo)題" />
<!--刪除按鈕-->
<Button
android:id="@+id/bt_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="刪除"/>
</LinearLayout>
正文結(jié)束
屬性android:descendantFocusability的值有三種:
beforeDescendants:viewgroup會(huì)優(yōu)先其子類控件而獲取到焦點(diǎn)
afterDescendants:viewgroup只有當(dāng)其子類控件不需要獲取焦點(diǎn)時(shí)才獲取焦點(diǎn)
blocksDescendants:viewgroup會(huì)覆蓋子類控件而直接獲得焦點(diǎn),也就是各有各的焦點(diǎn)