ExpandableListAdapter中getChild和getGroup调用时间?

程序员张晴天
  • 224

在ExpandableListAdapter的函数getChild()getGroup() getChildrenCount()添加Log

结果没有打出

getChildId()getChildView() getGroupId() getGroupView() getGroupCount()都被调用 并打出了log

想问问未打出log的3个函数分别在什么时候进行调用以及没有打log的原因

回复
阅读 5k
1 个回答
li21
  • 3.1k
✓ 已被采纳

关于getChildrenCount

点击展开GroupItem时,getChildrenCount()被调到,以返回这个Group的child数量(为避免出现数组越界的错误);然后adapter才会去调用getChildView()

@Override
public int getChildrenCount(int groupPosition) {
    Log.d(TAG, "getChildrenCount: groupPosition " + groupPosition);
    return count;
}

关于getChildView()、getChild()、getGroup()

我们需要覆写getChildView(),以填充视图,那么首先要拿到数据,而getChild()的目的就是拿到存储在adapter中对应位置的数据。
当然,如果你在adapter之外维护了一个child data list,也可以直接从这个list中取数据。
但是getChild()看起来不是更清楚明了吗?
getGroup()也是同样的道理,在执行getGroupView()填充group视图时,让你可以轻松地获取对应的数据。

private List mChildItems;

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
            View convertView, ViewGroup parent) {
    Log.d(TAG, "    getChildView: groupPosition" + groupPosition + ", childPosition " + childPosition);
    
    // 可以这样:
    HashMap<String, String> child = (HashMap<String, String>)getChild(groupPosition, childPosition);
    Log.d(TAG, "    child data from getChild():" + child.get("Sub Item"));
    
    // 也可以这样:
    Log.d(TAG, "    child data from my list:" + ((List)mChildItems.get(groupPosition)).get(childPosition));
    
    return view;
}

@Override
public Object getChild(int groupPosition, int childPosition) {
    Log.d(TAG, "    getChild: groupPosition" + groupPosition + ", childPosition " + childPosition);
    return super.getChild(groupPosition, childPosition);
}

部分方法调用的Log:

11-05 12:37:50.322: D/Exp(24030): getChildrenCount: groupPosition 1
11-05 12:37:50.325: D/Exp(24030):   getChildView: groupPosition1, childPosition 0
11-05 12:37:50.325: D/Exp(24030):     getChild: groupPosition1, childPosition 0
11-05 12:37:50.326: D/Exp(24030):     child data from getChild():Sub Item 0
11-05 12:37:50.326: D/Exp(24030):     child data from my list:{Sub Item=Sub Item 0}
11-05 12:37:50.329: D/Exp(24030):   getChildView: groupPosition1, childPosition 1
11-05 12:37:50.329: D/Exp(24030):     getChild: groupPosition1, childPosition 1
11-05 12:37:50.329: D/Exp(24030):     child data from getChild():Sub Item 1
11-05 12:37:50.329: D/Exp(24030):     child data from my list:{Sub Item=Sub Item 1}
11-05 12:37:50.331: D/Exp(24030):   getChildView: groupPosition1, childPosition 2
11-05 12:37:50.331: D/Exp(24030):     getChild: groupPosition1, childPosition 2
11-05 12:37:50.331: D/Exp(24030):     child data from getChild():Sub Item 2
11-05 12:37:50.331: D/Exp(24030):     child data from my list:{Sub Item=Sub Item 2}

本质上,ExpandableListAdapter 的getChild(), getGroup() 和 android.widget.Adapter 的 Object getItem(int position) 是一回事儿:『Get the data item associated with the specified position in the data set.』

参考:

宣传栏