Android ListView item點(diǎn)擊事件不響應(yīng)

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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容