---
title: "ListView Item 与子控件焦点问题    "
author: "zengyan2012"
date: "2013-02-07T17:11:00Z"
tags: []
categories: ["移动开发"]
slug: "listview-item"
draft: false
lastmod: "2013-02-07T17:19:28Z"
id: 1797346
url: "https://zengyan2012.iteye.com/blog/1797346"
---

在项目中，item中有3个控件，其中有2个控件是可以正常获取到焦点，但是第三个点击的时候，却出发了Item的点击事件。

 

#### android:descendantFocusability   // 放在listview中的item的顶级布局上。

 

Constant            Value        Description

`beforeDescendants`0    The ViewGroup will get focus before any of its descendants. //Item先获取到焦点

`afterDescendants`1      The ViewGroup will get focus only if none of its descendants want it. //子控件获取到焦点--- 也就是item无法获取到焦点

`blocksDescendants`2  The ViewGroup will block its descendants from receiving focus. //让子控件无法获取焦点 --事实证明子控件是可以获取到焦点的。

ListView默认情况

 

当item有焦点时，item上的button等子控件获取不到焦点；

当子控件有焦点时，item无焦点无法响应onItemClick事件

 

ViewGroup.FOCUS\_AFTER\_DESCENDANTS：表示item的子控件优先于item获得焦点；

ViewGroup.FOCUS\_BEFORE\_DESCENDANTS：表示item优先于其子控件获得焦点。

解决办法：

 

[view plain](http://www.verydemo.com/demo_c131_i8551.html)[print](http://www.verydemo.com/demo_c131_i8551.html)[?](http://www.verydemo.com/demo_c131_i8551.html)

01. listView.setOnItemSelectedListener(onItemSelectedListener);
02. private AdapterView.OnItemSelectedListener  onItemSelectedListener =
03. new AdapterView.OnItemSelectedListener(){
04. @Override
05. public void onItemSelected(AdapterView&lt;?&gt; parent, View view,
06. int position, long id) {
07. //当此选中的item的子控件需要获得焦点时
08. parent.setDescendantFocusability(ViewGroup.FOCUS\_BEFORE\_DESCENDANTS);
09. //else parent.setDescendantFocusability(ViewGroup.FOCUS\_BEFORE\_DESCENDANTS);
10. }
11. @Override
12. public void onNothingSelected(AdapterView&lt;?&gt; parent) {
13. parent.setDescendantFocusability(ViewGroup.FOCUS\_BEFORE\_DESCENDANTS);
14. }
15. }