我在“警报”对话框中设置默认选定项目时遇到一些问题。这是我在代码中使用的内容:
if(memory>megAvailable){
selected = 0;
} else if(megAvailable>memory){
selected = 1;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent());
builder.setTitle("Select Storage Path");
builder.setSingleChoiceItems(items, selected, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(item == 0){
rpc.createFoldersInInternalStorage(servername, userId, MyCollectionList.this);
Toast.makeText(getApplicationContext(), "Selected Storage Path : Phone Memory", Toast.LENGTH_SHORT).show();
editor.putInt("storagePath", 1);
editor.commit();
} else if (item == 1){
rpc.createFoldersInExternalStorage(servername, userId, MyCollectionList.this);
Toast.makeText(getApplicationContext(), "Selected Storage Path : SD Card", Toast.LENGTH_SHORT).show();
editor.putInt("storagePath", 2);
editor.commit();
}
}});
builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mHandlerUpdateUi.post(mUpdateUpdateUi);
}
});
AlertDialog alert = builder.create();
所以现在我的问题是我根据一些计算设置了所选项目,如果我没有选择任何内容并按OK,无论我是否选择了项目,默认它再次创建对话框,因为这是用户的想法没有选择任何东西。我试图设置item=selected;
或selected=item;
,但它不起作用。我知道我的问题是合乎逻辑的,但我无法弄清楚。有关如何让事情发挥作用的任何建议吗?
答案 0 :(得分:1)
您可以将设置storagePath的代码放在附加到NegativeButton的onClickHandler中:
final int defaultSelected = selected +1; //this is final since you need to access it in the anonymous inner class; we're adding 1 since your value that you write seems to be either 1 or 2.
builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mHandlerUpdateUi.post(mUpdateUpdateUi);
editor.putInt("storagePath", defaultSelected);
editor.commit();
}
});