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

来源:互联网 发布:天刀男性捏脸数据导入 编辑:程序博客网 时间:2024/06/06 14:29

在项目中会遇到这样的问题:自定义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.

ConstantValueDescriptionbeforeDescendants0The ViewGroup will get focus before any of its descendants.afterDescendants1The ViewGroup will get focus only if none of its descendants want it.blocksDescendants2The ViewGroup will block its descendants from receiving focus.

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