您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页ListView中Item与Checkable子类控件抢焦点问题

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 
    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>

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务