Android施用SimpleAdapter更新List…

Android使用SimpleAdapter更新ListView里面的Drawable元素

转自:http://www.cnblogs.com/thu539/archive/2012/02/01/2334455.html

 

最近在做一个扫描Android系统内已安装程序列表的小功能,需要将已安装程序信息读出来,找出其图标,并保存到一个List>中。方法如下:

 public void fetch_installed_apps(){
        List packages=getPackageManager().getInstalledPackages(0);
        list=new ArrayList>(packages.size());
        for(int i=0;i
            Map map=new HashMap();
            PackageInfo app=packages.get(i);
            if((app.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)==ApplicationInfo.FLAG_SYSTEM){//过滤掉系统程序
                Log.d("System software","We met System "+i+"th software: "+app.packageName);
                continue;
            }
            String packageName=app.packageName;
            String label="";
           
            try{
                label=app.applicationInfo.loadLabel(getPackageManager()).toString();
            }
            catch(Exception e){
                Log.i("Exception",e.toString());
            }
            if(label=="")continue;
            Drawable icon=null;
            icon=app.applicationInfo.loadIcon(getPackageManager()).getCurrent();//获得图标的Drawable信息
            map.put("img",icon);  //压入map中
            map.put("name", label);
            map.put("desc", packageName);
            list.add(map);  //将之加入List中
        }
        Log.d("fetch_installed_apps","Leave fetch!");
        return ;
    }

在获得已安装程序后的程序后,网上搜到的方法是使用SimpleAdapter更新ListView里面的数据:

SimpleAdapter notes=new SimpleAdapter(this,list,R.layout.info_row,
new String[]{"img","name","desc"},new int[]{R.id.img,R.id.name,R.id.desc});
itemlist.setAdapter(notes);

上面代码中的R.id.img是每行中ImageView的ID号,但是用这种方式,只能更新图像保存在res/drawable/下面的图像资源,如上面获取图片的代码改为:

int icon=R.id.image1;
map.put("img",icon);

否则,直接用SimpleAdapter更新一开始获取的Drawable类型的Icon的图像时,会出现错误:

I/System.out(284): resolveUri failed on bad bitmap uri: android.graphics.drawable.BitmapDrawable@485d7dd0

且显示结果如下:

查了很多资料,有说使用异步图像更新的方法,但是此处并非网络环境,还需要下载图片,所以没必要是用那个方式。经过查询资料,发现可以使用SimpleAdapter的ViewBinder方法来实现对Drawable或者Image类型图片的更新。其代码如下:

 SimpleAdapter notes=new SimpleAdapter(this,list,R.layout.info_row,
                new String[]{"img","name","desc"},new int[]{R.id.img,R.id.name,R.id.desc});
       
        itemlist.setAdapter(notes);
        notes.setViewBinder(new ViewBinder(){
            public boolean setViewValue(View view,Object data,String textRepresentation){
                if(view instanceof ImageView && data instanceof Drawable){
                    ImageView iv=(ImageView)view;
                    iv.setImageDrawable((Drawable)data);
                    return true;
                }
                else return false;
            }
        });
 

用这种方式,成功的实现了对图片的加载,显示效果如下,希望本文对大家有用!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值