安卓笔记侠

专注安卓开发

导航

ListView中Item与Checkable子类控件抢焦点问题

Android开发中,经常需要为ListView定制Adapter,绑定各种子类控件。
如果Item包含Button等Checkable的控件,那么就会发生点击Item无法响应的问题。原因是自己定义的Item中Button等Checkable控件先获取到了焦点。

解决方案有两种:

1.在ListView的Item的xml文件的根元素如LinearLayout中添加属性

android:descendantFocusability="blocksDescendants"
该属性定义了当View获取焦点时,viewGroup与子控件的关系:
beforeDescendants:viewgroup会优先子类控件而获取到焦点
afterDescendants:viewgroup当子类控件不需要获取焦点时才获取焦点
blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点
(测试第三个可以,第一个没反应。。。)

2.在Checkable控件中添加属性:
android:focusable="false"
android:clickable="true"
添加位置
 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2  android:id="@+id/linearLayout"
 3  android:layout_width="match_parent" 
 4  android:layout_height="match_parent" 
 5  android:orientation="horizontal" 
 6  android:descendantFocusability="blocksDescendants" > 
 7  <Button android:id="@+id/button" 
 8      android:layout_width="50dp" 
 9      android:layout_height="100dp" 
10      android:focusable="false" 
11      android:clickable="true" 
12      android:text="按钮"/>
13  <TextView 
14      android:id="@+id/textView" 
15      android:layout_width="50dp" 
16      android:layout_height="100dp"
17      android:focusable="false" 
18      android:clickable="true"
19      android:text="文本" />
20 </LinearLayout>

 

 

posted on 2017-10-11 21:11  安卓笔记侠  阅读(382)  评论(0编辑  收藏  举报