我需要在ExpandableListView中向扩展子节点的顶部添加标题。相同的标题应出现在所有展开的子项的顶部。我一直试图从适配器这样做:
public int getChildrenCount(int groupPosition) {
//Add one extra to children size
return mGroups.get(groupPosition).size()+1;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
//if childPosition 0 return the header
if(childPosition == 0)return convertView = mInflater.inflate(R.layout.child_header, null);
//childPosition -1 is the actual item
ChildItem childItem = (ChildItem) getChild(groupPosition, childPosition-1);
ChildViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.child_row, null);
} else {
holder = (ChildViewHolder) convertView.getTag();
}
if(holder == null){
holder = new ChildViewHolder(convertView);
convertView.setTag(holder);
}
holder.getTextLabel().setText(childItem.name);
holder.getPriceLabel().setText(String.valueOf(childItem.price));
return convertView;
}
ChildViewHolder处理在子行中查找视图。这似乎工作,但随后convertView将是除0以外的childPosition的R.layout.child_header。这会打破getTextLabel()调用。
有更好的方法吗?我真正想要的是这样的:
myExpandableListView.addChildHeaderView(new ChildHeader())
我通过创建像这样的视图而不是上面的
解决了这个问题if(convertView!=null){
holder = (ChildViewHolder) convertView.getTag();
}
if(holder == null){
convertView = mInflater.inflate(R.layout.child_row, null);
holder = new ChildViewHolder(convertView);
convertView.setTag(holder);
}
谢谢!
答案 0 :(得分:2)
对不起,迟到的回复,这是我的完整代码
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if(childPosition == 0)return convertView = mInflater.inflate(R.layout.child_header, null);
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ChildViewHolder holder = null;
ChildItem childItem = (ChildItem) getChild(groupPosition, childPosition-1);
//Get ViewHolder first
if(convertView!=null){
holder = (ChildViewHolder) convertView.getTag();
}
//If no ViewHolder, then create a new child row as convertView is probably a header
if(holder == null){
convertView = mInflater.inflate(R.layout.child_row, null);
holder = new ChildViewHolder(convertView);
convertView.setTag(holder);
}
holder.getTextLabel().setText(childItem.name);
holder.getPriceLabel().setText(String.valueOf(childItem.price));
return convertView;
}