android:descendantFocusability——父容器和子控件的焦点获取问题

 原文地址

在项目中会遇到这样的问题:自定义ListView的Item时,会出现点击每一项Item没有任何反应。我们重新来看一下自己定义的Item布局文件,一般这个时候自定义的Item布局文件中都会出现类似于Button、ImageButton、CheckBox等子控件。而这些子控件率先获取了ListView的Item的焦点,使得我们点击ListView的每一项Item的时候,就出现了点击哪一项都没有反应的情况。

我们来看Android官方文档是怎么给出解决方案的:

public static final int descendantFocusability
Added in  API level 1

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.

Constant Value Description
beforeDescendants 0 The ViewGroup will get focus before any of its descendants.
afterDescendants 1 The ViewGroup will get focus only if none of its descendants want it.
blocksDescendants 2 The ViewGroup will block its descendants from receiving focus.

Constant Value: 16842993 (0x010100f1)
通过android:descendantFocusability这个属性可以解决上面的问题。这个属性定义了当一个焦点要传递给父容器或者子控件时,父容器和子控件之间获得焦点的关系。具体值如下:
beforeDescendants:父容器会比其子控件率先获得焦点。
afterDescendants:如果没有任何子控件要获得焦点的话,那么父容器才会获得焦点。
blocksDescendants:父容器会阻止其子控件获得焦点(也就是说焦点会由父容器获得)。
所以最后的解决方案是:在自定义的Item布局文件的根布局中加上android:descendantsFocusability="blocksDescendants"
就可以了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值