ExpandableListView 添加其他控件

来源:互联网 发布:中文文本词性标注算法 编辑:程序博客网 时间:2024/06/10 18:18
可折叠式的list控件使用系统的SimpleExpandableListAdapter 在每一项里添加图片时老是报错,
在网上查了些资料大部分提供的解决方案是自定义一个Adapter 继承BaseExpandableListAdapter的方式,感觉忒麻烦了,于是就根据错误信息看了看系统SimpleExpandableListAdapter的源码  关键代码如下:
SimpleExpandableListAdapter .java

private void bindView(View view, Map<String, ?> data, String[] from, int[] to) {
        int len = to.length;

        for (int i = 0; i < len; i++) {
            View viewItem=view.findViewById(to[i]);
                TextView v = (TextView)view.findViewById(to[i]);
                if (v != null) {
                    v.setText((String)data.get(from[i]));
                }
            }
           
        }
    }
果然,他将每一项都看成一个TextView 了,难怪不能添加图片,我们只需添加小小判断就可满足需求
修改后如下:
private void bindView(View view, Map<String, ?> data, String[] from, int[] to) {
        int len = to.length;

        for (int i = 0; i < len; i++) {
            View viewItem=view.findViewById(to[i]);
            if(viewItem instanceof TextView){
                TextView v = (TextView)view.findViewById(to[i]);
                if (v != null) {
                    v.setText((String)data.get(from[i]));
                }
            }else if(viewItem instanceof ImageView){
                ImageView imgView =(ImageView) view.findViewById(to[i]);
                if(imgView!=null){
                imgView.setImageResource(new Integer(data.get(from[i]).toString()));
                }
                
        }
    }
我这里只加了ImageView 的判断,已经满足了我的需求,当然如果需要别的控件的话,可以再加其他判断。
这样比自定义适配器省事多了
原创粉丝点击