我想显示已安装应用程序的列表,用户可以在这样的列表中选择多个应用程序。 到目前为止,我非常成功,显示了图标,但在列表操作时卡住了:触摸时不会选择项目,而且我也不知道如何在用户完成后检索所选项目。
代码:
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();
最佳答案
我已经在我的一个应用程序中实现了这一点。您可以通过为您的 ListView 创建一个自定义适配器并在每行中放置一个复选框以及一个用于存储所选项目名称的字符串数组来实现这一点。现在实现 checkchange 监听器在适配器的 getView() 中,如果检查为真,则在名称数组中的位置的帮助下添加列表项,反之亦然。希望你明白我的意思...
关于android - 带图标的 AlertDialog MultiChoiceItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544930/