ListViewの子要素(ListItem)にButtonを設置したら、ListItemのonClickListenerが呼ばれなくなっちゃった。
ButtonとListItemでそれぞれ別の挙動をさせたいのに困った。
AndroidのListViewって、ListItemをAdapterからじゃんじゃんつくって、
ListItemにタッチしたときのイベントはsetOnClickListenerで設定すればOK。
でも、ListItemにButtonを設置すると(レイアウトXMLとかで)、ButtonのonClickListenerは使えるんだけども、ListItemでつかえていたonClickListenerがブロックされちゃう。
どうやらListItemの子要素にButtonとかのクリックできるWidgetが入ってくるとブロックするように作ってあるみたい。当然か。
そのブロックを解除する方法はこんな感じ。
ListItemのレイアウトを指定しているlayout_hogehoge.xmlのルート要素(RelativeLayoutとかFrameLayout)の属性に
android:descendantFocusability="blocksDescendants"
を追加。
具体的には
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="3dip" android:descendantFocusability="blocksDescendants" android:orientation="horizontal"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="3dip" android:background="#ffffff"> <ImageView android:id="@+id/list_planning_imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@string/app_name" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/list_planning_name" android:layout_width="0dip" android:layout_height="wrap_content" android:text="@string/app_name" android:layout_weight="1" /> <TextView android:id="@+id/list_planning_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </LinearLayout> <FrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > </FrameLayout> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </FrameLayout>
こんなかんじ。そしたら下の画像みたいな感じでもListItemとButtonそれぞれでタップできるよ!
ご参考:
日本Androidの会 › リストビューの行に置いたボタンhttps://groups.google.com/forum/?fromgroups=#!topic/android-group-japan/txDNa2DA5W8
android ListView onItemClick イベントが発生しない!http://falco.sakura.ne.jp/tech/2012/11/android-listview-onitemclick-%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88%E3%81%8C%E7%99%BA%E7%94%9F%E3%81%97%E3%81%AA%E3%81%84%EF%BC%81/
ListViewの中のボタンからActivityにイベントを通知する http://atgb.cocolog-nifty.com/astimegoesby/2011/02/listviewactivit.html