大家都知道listview可以根据自己的需求,重写baseadapter ,实现自己的布局及数据,但是当我们在自己的布局中加入了button或者ImageButton,还有其他比如checkbox,radiobutton等控件时,发现listview不在响应onitemclick事件,让人很悲愤啊,自己在网找了个方法,可以处理掉这个东东
发生的原因:当listview中包含button,checkbox等控件的时候,android会默认将focus给了这些控件,也就是说listview的item根本就获取不到focus,所以导致onitemclick时间不能触发。
既然我们知道了,发生的原因,那么我们就将button等控件的在xml布局文件中的属性android:focusable设置为false,就ok了,但通常不这样做,因为要一个一个地修改button太麻烦,通常可以修改这些button的父容器的descendantFocusability属性为false,是否很方便呢,这样即可以触发onitemclick事件,同时我们在baseadapter实现类中也可以处理button等控件的事件,两不相误。
1.list.xml
- <?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="match_parent"
- android:orientation="vertical" >
- <ListView android:id="@+id/list"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- </ListView>
-
- </LinearLayout>
2.list_item.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:descendantFocusability="blocksDescendants"
- android:orientation="horizontal" >
- <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
- android:text="你好吗?"
- android:id="@+id/text"
- />
- <Button android:id="@+id/button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:focusable="false"
- android:text="确定"
- />
-
- </RelativeLayout>