android get alert dialog default selected item

眉间皱痕 提交于 2020-01-06 02:35:11

问题


I have a little problem with setting the default selected item in Alert Dialog. Here is what I use in my code :

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

So my problem now is I set the selected item depending on some calculations and if i don't select anything and press OK, no matter that I have selected item by default it's creating the dialog again, because that's the idea if user didn't select anything. I've tried to set item=selected; or selected=item; but it's not working. I know my problem is logical , but I can't figure it out. Any suggestions how to get the things to work?


回答1:


You can just put the code that sets your storagePath in the onClickHandler attached to the NegativeButton:

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


来源:https://stackoverflow.com/questions/8184514/android-get-alert-dialog-default-selected-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!