我正在我的应用程序开头创建一个警报对话框,让用户选择存储我的应用程序从网上下载的数据的位置。我现在想要实现的是取决于我想要设置所选项之一的内部/外部存储的大小。这是我用来创建对话框的代码:
@SuppressWarnings("static-access")
public void createDialog(){
final CharSequence[] items = {"Phone Memory - "+memorysize+" free space", "SD Card - "+megAvailable+" MB free space"};
final int userId = rpc.getUserId(this);
final String servername = rpc.getCurrentServerName(this);
SharedPreferences stampiiSettings = PreferenceManager.getDefaultSharedPreferences(MyCollectionList.this);
final SharedPreferences.Editor editor = stampiiSettings.edit();
AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent());
builder.setTitle("Select Storage Path");
builder.setSingleChoiceItems(items, -1, 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.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mHandlerUpdateUi.post(mUpdateUpdateUi); // update UI
}
});
AlertDialog alert = builder.show();
}
另一件我想要实现的事情,如果他没有选择任何项目,如何阻止用户关闭警报对话框。我不想在按下后退按钮或单击确定按钮时关闭对话框。欢迎任何想法/建议/帮助!
答案 0 :(得分:18)
做这样的事情:
int selected = 0; // or whatever you want
builder.setSingleChoiceItems(items, selected, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//onclick
}});
答案 1 :(得分:3)
关闭按钮,您可以像这样定义取消按钮
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// no need to write anything here just implement this interface into this button
}
});
对于所选项,您可以将微调器作为此类的本地定义,也可以将此值指定给任何变量(如选定的)。
int selected = 0; // if you want in integer or
String selected = "internal"; // you can go with string
现在您可以将默认值设置为此值,并在单击对话框的“确定”按钮时获取值
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here get the selected item value
}
});