效果图

初使化
在使用SimpleAdapter绑定数据时,如果ImageView控件的数据来源是Drawable则显示失败,因为默认图片显示控件绑定的是id值
public class DesktopActivity extends BaseActivity implements AdapterView.OnItemClickListener
private List<Map<String, Object>> lstData; //储存应用名和图标
private List<String> lstPackage; //储存应用包名,与应用名进行对应
private SimpleAdapter simpleAdapter;
取得系统应用数据
private void getData() {
List<PackageInfo> packageInfoList = getPackageManager().getInstalledPackages(0);
for (int p = 0; p < packageInfoList.size(); p++) {
PackageInfo packageInfo = packageInfoList.get(p);
//取得用户安装应用,else则为系统应用
if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
Map<String, Object> map = new HashMap<String, Object>();
//应用程序图标
map.put("image", packageInfo.applicationInfo.loadIcon(getPackageManager()));
//应用程序显示名称
map.put("label", packageInfo.applicationInfo.loadLabel(getPackageManager()).toString());
lstData.add(map);
//应用程序包名
lstPackage.add(packageInfo.packageName);
}
}
}
初使化 Adapter
由于取得的系统用户安装应用数据中,应用图标为 drawable 类型,无法直接使用 SimpleAdapter 直接赋值,需要更改数据绑定方法
lstData = new ArrayList<Map<String, Object>>();
getData();
simpleAdapter = new SimpleAdapter(this, lstData, R.layout.widget_desktop_item, new String[]{
"image", "label"}, new int[]{
R.id.iv_widget_desktop_icon, R.id.tv_widget_desktop_label});
//重写数据绑定方式
simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Object o, String s) {
if(view instanceof ImageView && o instanceof Drawable){
ImageView iv = (ImageView)view;
iv.setImageDrawable((Drawable)o);
//调整图片大小
//RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.MATCH_PARENT);
//layoutParams.width = Integer.parseInt(viewBinding.etDesktopIconsize.getText().toString().trim());
//layoutParams.height = Integer.parseInt(viewBinding.etDesktopIconsize.getText().toString().trim());
//iv.setLayoutParams(layoutParams);
return true;
}else {
return false;
}
}
});
viewBinding.gvDesktopAppGroup.setAdapter(simpleAdapter);
绑定事件
应用程序显示出来后,我们还要实现他点击之后能够打开相应的应用
系统应用有些属于无界面服务类的,所以,可能点击之后没反应
viewBinding.gvDesktopAppGroup.setOnItemClickListener(this);
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch (adapterView.getId()) {
case R.id.gv_desktop_app_group:
//根据应用的 package 包名启动外部应用程序
Intent intent = getPackageManager().getLaunchIntentForPackage(lstPackage.get(i));
if (intent != null) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
break;
}
}