2

我想显示已安装应用程序的列表,用户可以在该列表中选择多个应用程序。到目前为止,我非常成功,显示了图标,但陷入了列表操作:触摸时没有选择项目,而且我也不知道如何在用户完成后检索选定的项目。

代码:

PackageManager pm = getPackageManager(); //get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
final ArrayList<AppsItem> apps = new ArrayList<AppsItem>(packages.size());
for (ApplicationInfo packageInfo : packages)
{
  log.i("getting package list", "Installed package : %s  name %s", packageInfo.packageName, pm.getApplicationLabel(packageInfo));
  apps.add(new AppsItem(packageInfo.packageName, pm.getApplicationIcon(packageInfo), pm.getApplicationLabel(packageInfo).toString()));
}
Collections.sort(apps);

final ListAdapter adapter = new ArrayAdapter<AppsItem>(this, android.R.layout.select_dialog_multichoice, android.R.id.text1, apps)
{
  public View getView(int position, View convertView, ViewGroup parent)
  {
    //User super class to create the View
    View v = super.getView(position, convertView, parent);
    CheckedTextView tv = (CheckedTextView) v.findViewById(android.R.id.text1);
    final AppsItem itm = apps.get(position);

    tv.setText(itm.appText);
    //Put the image on the TextView
    tv.setCompoundDrawablesWithIntrinsicBounds(itm.icon, null, null, null);
    tv.setChecked(itm.selected);

    tv.setOnClickListener(new OnClickListener()
    {
      public void onClick(View view)
      {
        CheckedTextView v = (CheckedTextView) view;
        itm.selected = !itm.selected;
        v.setChecked(itm.selected);
      }
    });

    //Add margin between image and text (support various screen densities)
    int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
    tv.setCompoundDrawablePadding(dp5);

    return v;
  }
};

AlertDialog.Builder alert = new AlertDialog.Builder(Settings.this);

alert.setTitle(rTitle);
alert.setAdapter(adapter, null);
alert.setPositiveButton(TX.s(android.R.string.ok), new DialogInterface.OnClickListener()
{
  @Override
  public void onClick(DialogInterface dialog, int which)
  {
    String selApps = "";
    for (AppsItem app: apps)
      if (app.selected)
        selApps += app.appID + ",";
    if (selApps.length() > 0)
      selApps = selApps.substring(0, selApps.length() - 1);
    log.i("app selection", "selected apps: %s", selApps);            
  }}); //How to retrieve the clicked items here?
alert.setNegativeButton(TX.s(android.R.string.cancel), null);
alert.show();
4

1 回答 1

1

我已经在我的一个应用程序中实现了这一点。您可以通过为列表视图创建一个自定义适配器并在每一行中放置一个复选框以及一个用于存储所选项目名称的字符串数组来实现这一点。现在在 getView( ) 您的适配器,如果检查为真,则在名称数组中的位置的帮助下添加列表项,反之亦然。希望你明白我的意思...

于 2013-01-27T07:16:28.230 回答