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

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

解决方案有两种:

  1. 在ListView的Item的xml文件的根元素如LinearLayout中添加属性
    android:descendantFocusability="blocksDescendants"
    API:android:descendantFocusability
    Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.
    Must be one of the following constant values.


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

  2. 在Checkable控件中添加属性:
    android:focusable="false"
    android:clickable="true"
    添加位置

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal" 
    android:descendantFocusability="blocksDescendants" > 
    <Button android:id="@+id/button" 
        android:layout_width="50dp" 
        android:layout_height="100dp" 
        android:focusable="false" 
        android:clickable="true" 
        android:text="按钮"/>
    <TextView 
        android:id="@+id/textView" 
        android:layout_width="50dp" 
        android:layout_height="100dp"
        android:focusable="false" 
        android:clickable="true"
        android:text="文本" />
</LinearLayout>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容