在expandListView的group中如果包含imageview发现,报错。提示无法将imageview转换成TextView.查看源码发现,SimpleExpandableListAdapter中有如下方法:
private void bindView(View view, Map<String, ?> data, String[] from, int[] to) { int len = to.length; for (int i = 0; i < len; i++) { TextView v = (TextView)view.findViewById(to[i]); if (v != null) { v.setText((String)data.get(from[i])); } } }
可以看出bindView把所有view都当textView来处理了。真是完全没有老大哥simpleAdapter的防范,可以自动判断类型绑定。网上普遍给出的方法是重写bindView方法:
public class MyExpandableListAdapter extends BaseExpandableListAdapter{ private void bindView(View view, Map<String, ?> data, String[] from, int[] to) { int len = to.length; boolean isBound = false; for (int i = 0; i < len; i++) { final View v = view.findViewById(to[i]); if (v!=null) { final Object _data = data.get(from[i]); String text = _data == null ? "" : data.toString(); if (text == null) { text = ""; } if (mViewBinder != null) {//如果Binder不为空,使用Binder进行处理 isBound = mViewBinder.setViewValue(v, data.get(from[i]), text); } if (!isBound) {//如果Binder跳过,使用原来的方法进行处理 TextView _v = (TextView)v; _v.setText((String)data.get(from[i])); } } } } }
不过对于我来说,尽量不重写SDK没有建议你复写的方法,因为复写之后性能和安全很难保证,最好能让原SDK去处理。继续查看源代码,发现当我们返回的类型不是一个view类型,而是一个确切的布局类型时,sdk就能识别,并不再当TEXTview处理,所以我的处理方案是将convertview转换成我那个layout文件的布局类型:
@Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { ItemViewHolder holder = null; if(convertView == null){ holder=new ItemViewHolder(); convertView = inflater.inflate(R.layout.down_exam_vitem, null); holder.itemImg = (ImageView)convertView.findViewById(R.id.exam_vitem_img); convertView.setTag(holder); }else{ holder = (ItemViewHolder)convertView.getTag(); } itemView = (RelativeLayout)convertView; return itemView; }
时间: 2024-10-03 15:48:22