美文网首页
ListView Item 与子控件焦点问题

ListView Item 与子控件焦点问题

作者: 木猫尾巴 | 来源:发表于2016-11-22 11:59 被阅读243次

[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);
    }
}

相关文章

网友评论

      本文标题:ListView Item 与子控件焦点问题

      本文链接:https://www.haomeiwen.com/subject/hgmppttx.html