[TOC]
表現
item中有3個控件,其中有2個控件是可以正常獲取到焦點,但是第三個點擊的時候,卻出發了Item的點擊事件。
原因
ListView默認情況時
- 當item有焦點時,item上的button等子控件獲取不到焦點;
- 當子控件有焦點時,item無焦點無法響應onItemClick事件;
解決策略
ListView XML 屬性
放在listview中的item的頂級布局上
android:descendantFocusability
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. 讓子控件無法獲取焦點 --事實證明子控件是可以獲取到焦點的 |
ViewGroup 關于焦點的策略參數
- ViewGroup.FOCUS_AFTER_DESCENDANTS:表示item的子控件優先于item獲得焦點;
- ViewGroup.FOCUS_BEFORE_DESCENDANTS:表示item優先于其子控件獲得焦點。
listView.setOnItemSelectedListener(onItemSelectedListener);
private AdapterView.OnItemSelectedListener onItemSelectedListener =
new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
//當此選中的item的子控件需要獲得焦點時
parent.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
//else parent.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
parent.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
}
}