我需要创建一个包含多项选项的AlertDialog,但是我在尝试将自定义布局文件设置为内部ListView时遇到了一些麻烦.
对于单选项,我使用一个构造函数,它将ListAdapter作为参数,这样我就可以为每一行设置合适的布局资源:
builder.setSingleChoiceItems(new ArrayAdapter<String>(getActivity(),
R.layout.list_item_single_choice_answer, items), checkedItem,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
checkedItem = which;
toggleEditTextAnswer(checkedItem == (items.length - 1));
dialog.dismiss();
}
});
问题是setMultiChoiceItems没有构造函数在创建多选列表时接受ListAdapter作为参数.
我需要为每一行设置一个自定义布局,因为我使用drawable选择器来设置行背景和文本颜色.
有任何想法吗?
PS.这里是AlertDialog源代码以获取更多信息.
https://android.googlesource.com/platform/frameworks/base.git/+/android-4.2.2_r1/core/java/android/app/AlertDialog.java
解决方法:
好吧,我知道我应该创建一个自定义对话框,但现在我没有时间去做…所以这就是我破解这个问题的方法:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the adapter
builder.setAdapter(
new ArrayAdapter<String>(getActivity(),
R.layout.list_item_multiple_choice_answer, items), null)
// Set the action buttons
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
ListView listView = alertDialog.getListView();
listView.setAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.list_item_multiple_choice_answer, items));
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView checkedTextView = (CheckedTextView) view;
checkedItems[position] = !checkedTextView.isChecked();
}
});
listView.setDivider(null);
listView.setDividerHeight(-1);
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
setCheckedItems(((AlertDialog) dialog).getListView());
}
});
alertDialog.show();
首先,我使用项目设置适配器,而不是调用setMultiChoiceItems,我从Dialog中获取ListView对象,然后自己配置它.