Showing posts with label ListView. Show all posts
Showing posts with label ListView. Show all posts

Friday, September 7, 2012

ListView裡的OnItemClickListener失去作用(失效)

一、Problem
今天在實作ListView,自訂義一個Adapter繼承BaseAdapter後,
發現ListView原本的OnItemClickListener失去作用。

二、Description
上圖是ListView的其中一橫條,
為了讓內容豐富,
用了2個ImageView(圖片)和2個TextView(文字)元件。
有時候為了讓ListView的內容豐富,
我們常會自訂義一個Layout來讓ListView的內容多元,
但也因為多元,
如上圖所示,ImageView和TextView預設都有自己獲得Focus的能力,
這些元件搶走了原本List獲得焦點的能力。

每一條ListView在點擊時,
原本都擁有自己的Focus,
因此ListView的點擊才有效用。

如果我們希望List被點擊後,
讓OnItemClickListener仍有作用,
該怎麼做呢?

三、Solution
外國論譠描述要改善子元件不影響原來ListView獲得Focus最快的方式就是在自訂義的Layout中,附上一個屬性︰

下片這段程式碼就是上面List_Item內容的Layout佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/feeback_item_bg"
    android:gravity="center_vertical"
    android:descendantFocusability="blocksDescendants">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="3dp"
        android:layout_marginLeft="10dp"
        android:text="題編"
        android:textColor="#FFFFFF"
        android:textSize="8sp" />


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/feedback_q" />

<TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingBottom="5dp"
        android:singleLine="false"
        android:text="題目內容"
        android:textColor="#000000" />


    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/feedback_a" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:inputType="text|textMultiLine"
        android:paddingRight="20dp"
        android:text="答案"
        android:textColor="#000000" />

</LinearLayout>

如上面紅色標註,
Android有提供一個快捷方式讓Layout裡的子元件全部失焦,
就是使用
android:descendantFocusability="blocksDescendants"

註︰
1.當我在使用這個屬性時,
仍然無法讓OnItemClickListener發揮作用,
後來才發現我的TextView裡原本有設定一個屬性android:inputType="textMultiLine"
外國網友討論說這是一個Android的BUG,
此屬性一旦宣告,
又會讓上面紅色的宣告失去效果。
我把inputType="textMultiLine"拿掉,
整個問題才被解決。 
2.最好用RelativeLayout的方式,使用僅一層Layout的架構客製這個list_item,
不僅在滑動有效率,也不會有這篇產生的問題。