安卓如何在警告对话框中设置选定项目

10

我正在创建一个警告对话框,在我的应用程序开始时让用户选择将从Web下载的数据存储在何处。现在我想实现的是根据内部/外部存储的大小,我想设置其中一个项目为已选择。下面是我用来创建对话框的代码:

@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();
}

还有一件我想要实现的事情,如何防止用户在没有选择任何选项的情况下关闭弹出对话框。我不希望用户在按下返回按钮或点击确定按钮时关闭对话框。欢迎任何想法/建议/帮助!

2个回答

24

可以尝试这样做:

int selected = 0; // or whatever you want
builder.setSingleChoiceItems(items, selected, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
              //onclick
    }});

3

为关闭按钮,您可以通过以下方式定义取消按钮:

cancelButton: 'ok'
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
        }
});

对于所选项目,您可以将旋转器作为此类的本地定义,也可以将该值分配给任何变量,如selected。

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 
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接