我试图用带有图标的适配器设置AlertDialog方法,setMultiChoiceItems,但是它接受的唯一方法是setSingleChoiceItems,但它必须是多重的。用户单击按钮并显示一个对话框,其中包含他可以选择的图标。我已经搜索了有关alert.dialog,适配器的文档,我确实没有发现任何相关内容。问题是,如何创建适配器或在对话框中设置字符串和图像图标的东西。
我的代码:
final String [] items = new String[] {"Music", "Sport"};
final Integer[] icons = new Integer[] {R.drawable.iconmusictest, R.drawable.iconsporttest};
ListAdapter adapter = new ArrayAdapterWithIcon(Register30.this, items, icons);
AlertDialog.Builder builder = new AlertDialog.Builder(Register30.this);
builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
}
})
.setTitle("Select your likes")
.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog popUpLikes = builder.create();
我的类返回自定义适配器:
public class ArrayAdapterWithIcon extends ArrayAdapter<String> {
private List<Integer> images;
public ArrayAdapterWithIcon(Context context, String[] items, Integer[] images) {
super(context, android.R.layout.select_dialog_item, items);
this.images = Arrays.asList(images);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view.findViewById(android.R.id.text1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(images.get(position), 0, 0, 0);
} else {
textView.setCompoundDrawablesWithIntrinsicBounds(images.get(position), 0, 0, 0);
}
textView.setCompoundDrawablePadding(
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, getContext().getResources().getDisplayMetrics()));
return view;
}
}
答案 0 :(得分:-1)
boolean[] checkedItems = new boolean[items.length];
for (int i = 0; i < items.length; i++) {
if (selectedItems.contains(i)) {
checkedItems[i] = true;
} else {
checkedItems[i] = false;
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMultiChoiceItems(items, checkedItems, new
DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int indexSelected,
boolean isChecked) {
if (isChecked) {
selectedItems.add(indexSelected);
}
else if (selectedItems.contains(indexSelected)) {
selectedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// TODO
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
filterDialog.dismiss();
}
});