java – Android:Dialog Builder multipleselection设置数组
作者:互联网
我正在尝试按照Android文档关于多个选择对话框.我有一个问题,我认为这是我正在尝试加载的数组类型.
public void addCondition(View view){
ArrayList<String> mHelperNames= new ArrayList<String>();
mHelperNames.add("Test Item");
mHelperNames.add("Test Item");
mHelperNames.add("Test Item");
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title")
.setMultiChoiceItems(mHelperNames, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//Create onlcick method
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//Create onlcick method
}
});
builder.show();
}
上面是我的代码,但它是eclipse中的红线城市:
在文档中,mSelectedItems永远不会被声明,我不太确定我将其声明为什么.
.SetMultipleChoiceItems上的错误是:
AlertDialog.Builder类型中的方法setMultiChoiceItems(int,boolean [],DialogInterface.OnMultiChoiceClickListener)不适用于参数(ArrayList,null,new DialogInterface.OnMultiChoiceClickListener(){})
但是,如果我从字符串中更改它,如何在其中显示文本项?任何帮助将非常感激.
汤姆
解决方法:
您必须为setMultiChoiceItems方法提供CharSequence [],而不是ArrayList.
您可以像这样创建mHelperNames:
CharSequence[] mHelperNames = new CharSequence[] { "test item 1", "test item 2" };
并且不要忘记声明mSelectedItems:
final List<Integer> mSelectedItems = new ArrayList<Integer>();
(它必须是最终的,因为你从内部类访问它)
如果需要稍后修改,也可以将mHelperNames保留为ArrayList.然后,在调用setMultiChoiceItems时需要将其转换为数组:
List<CharSequence> mHelperNames = new ArrayList<CharSequence>();
mHelperNames.add("Test Item 1");
mHelperNames.add("Test Item 2");
final List<Integer> mSelectedItems = new ArrayList<Integer>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title")
.setMultiChoiceItems(mHelperNames.toArray(new CharSequence[mHelperNames.size()]), null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer
.valueOf(which));
}
}
})
标签:android,java,android-dialog 来源: https://codeday.me/bug/20190729/1570261.html