安卓学习androidAndroid开发

ListView中增加checkbox导致item点击事件失效

2016-10-03  本文已影响1162人  AlanGuo

记录一下今天碰到一个神奇的问题——在一个ListView的自定义Item的布局中加入了一个CheckBox,结果怎么都无法触发长按事件……

找了好久终于在网上找到了一个简单的解决办法:
http://blog.csdn.net/lr393993507/article/details/38110337

简而言之,这是一个View的焦点抢占问题。由于里面有Item里面包含了一个CheckBox(类似情况还包括Button、ImageButton等本身带有click等事件的View),此时此 item 的区域内,event 的焦点被内部的 View 抢占了,也就是说只能触发内部 View 的点击事件,而 Item 的点击事件无法被触发。

我们要做的,就是处理好View的descendantFocusability属性,该属性是当一个为view获取焦点时,定义viewGroup和其子控件两者之间的关系。

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:
beforeDescendants:viewgroup会优先其子类控件而获取到焦点
afterDescendants:viewgroup只有当其子类控件不需要获取焦点时才获取焦点
blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点

一般来说我们使用第三种 blockDescendants,简单的解决办法就是在自定义item的布局中的根布局中指定 android:descendantFocusability="blocksDescendants"

mycell.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_height="120dp"
    android:layout_width="match_parent"
    android:descendantFocusability="blocksDescendants"> <!--Look at here-->
    <GridLayout
        android:layout_weight="3"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/AndroidStudioLight">

    </GridLayout>
    <LinearLayout
        android:layout_weight="1"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:background="@color/AndroidStudioLight">
        <TextView
            android:id="@+id/taskTitle"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="hehe"
            android:textSize="20dp"
            android:gravity="center"/>
        <TextView
            android:id="@+id/taskDetail"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="hehe"
            android:textSize="15dp"
            android:textColor="@color/gray"
            android:gravity="center"/>
    </LinearLayout>
    <GridLayout
        android:background="@color/AndroidStudioLight"
        android:layout_weight="3"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <CheckBox
            android:layout_gravity="center"/>
    </GridLayout>
</LinearLayout>
上一篇下一篇

猜你喜欢

热点阅读