這兩天在搗鼓ListView widget,爲了在ListView中加入Button這類的有 “點擊” 事件的widget,請教了不少高手,感謝LandMark對我的認真講解,下面把解決過程描述一下。
ListView 和 其它能觸發點擊事件的widget無法一起正常工作的原因是加入其它widget後,ListView的itemclick事件將無法觸發,被其它widget的click事件屏蔽。
首先,說明一下,ListView中每一行包括以下三項:
一個ImageView, 一個TextView,一個ImageButton,依次排開。
以下是layout的內容,分爲兩部分:
res/layout/main.xml
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:padding="10dip" android:orientation="vertical">
<ListView android:id="@id/android:list" android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
|
因爲繼承了ListActivity,所以ListView 的id設置爲"@id/android:list"是必須的
res/layout/lvitem.xml
注意:
在<RelativeLayout>中
android:descendantFocusability="blocksDescendants"
和<ImageButton>中
android:focusable="false"
這兩項的設置很關鍵,如果不設置,將導致ListView的ItemClick事件將無法觸發,該事件被ImageButton的click事件屏蔽了。
<?xml version="1.0"encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip"
android:descendantFocusability="blocksDescendants">
<ImageView
android:id="@+id/ItemImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip"
/>
<!--
把按鈕背景設置爲透明: android:background="#00000000"
把按鈕背景設置爲半透明: android:background="#e0000000"
-->
<ImageButton
android:id="@+id/ItemCloseWin"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/ItemWinName"
android:layout_alignBottom="@+id/ItemWinName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#e0000000"
android:gravity="left|center_vertical"
android:focusable="false"
android:src="@android:drawable/ic_menu_close_clear_cancel"
/>
<TextView
android:id="@+id/ItemWinName"
android:layout_toRightOf="@+id/ItemImage"
android:layout_toLeftOf="@+id/ItemCloseWin"
android:layout_alignTop="@+id/ItemImage"
android:layout_alignBottom="@+id/ItemImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:textSize="20dip"
android:text="title"
/>
</RelativeLayout>
|