【Android問題集】ListView不響應onItemClick事件

作者:Yogi

前言:在機頂盒的直播應用項目中遇到listview完全不響應onItemClick事件,但是響應onItemSelected事件,這個問題該怎麼解決呢?

解決思路

listView不響應onItemClick事件,有以下幾個原因

1.應用卡死了

2.根本就沒有setOnItemClickListener

3.listview沒有獲取到焦點

4.click事件被listview上的子控件消化了

分析

首先,我的應用沒有卡死,所以可能性1排除了。查看代碼之後,可能性2也排除了。
在Activity的dispatchKeyEvent方法中通過添加如下代碼(打印當前獲取了焦點的控件)

 Log.d(TAG, "current focus= " + getWindow().getCurrentFocus());

發現listview是有焦點的。所以可能性3也被排除了。只剩下可能性4了。
通過查看item的佈局文件(以下是部分佈局文件代碼)

<LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="@dimen/channel_nav_open_height"
    android:clickable="true"
    android:focusable="true"
    android:orientation="horizontal" >

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="@dimen/channel_nav_open_height" >

        <ImageView
            android:id="@+id/group_icon"
            android:layout_width="@dimen/channel_nav_close_icon_width"
            android:layout_height="@dimen/channel_nav_close_icon_height"
            android:src="@drawable/nav_icon_a_nor" />

        <TextView
            android:id="@+id/nav_icon_number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="45dp"
            android:layout_marginTop="30dp"
            android:textColor="@color/white"
            android:textSize="20sp"
            android:visibility="gone" />
    </FrameLayout>

    <TextView
        android:id="@+id/group_name"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="@dimen/channel_nav_open_item_name_margin_top"
        android:background="#00000000"
        android:textColor="@drawable/nav_textcolor"
        android:textSize="@dimen/channel_nav_open_item_name_text_size" />

</LinearLayout>

可以看到第4行和第5行都爲true,所以說,click事件被子控件消化了,去掉這2行(或者置爲false),listview果然能響應onItemClick事件了。

總結

這個問題很簡單,這篇日誌主要是爲了引出解決問題的思路。
解決問題之前,一定要把思路理清楚,先把問題的可能性都列出來,然後通過一系列的驗證,得到問題發生的真正原因。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章