简体   繁体   中英

Activity not waiting for Dialog to exit

In the following code I am trying to get String input for a folder name using AlertDialog, but the Activity is not waiting for the dialog to exit and the folderName gets the value null , as soon as the dialog shows up. My Question is how to make it wait for the input ?

My Code

     public boolean onOptionsItemSelected(MenuItem item)
     {
        switch(item.getItemId())
        {
            case 5:
            LayoutInflater li = LayoutInflater.from(this);
            View promptsView = li.inflate(R.layout.prompts,null);
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

            alertDialogBuilder.setView(promptsView);

            final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);

            alertDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int id) 
                {
                    MainActivity.this.folderName = userInput.getText().toString();
                }

            }).setNegativeButton("Cancel",new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int id) 
                {
                    dialog.cancel();
                }
            });
            try
            {
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
                Log.d("create folder","folder name : "+folderName);
                $mkdir(curDir,folderName);
            }
            catch(Exception e)
            {
                this.displayToast("Exception : "+e);
            }
            return true;
           }
        }

Move this code:

Log.d("create folder","folder name : "+folderName);
            $mkdir(curDir,folderName);

To

public void onClick(DialogInterface dialog, int id) 
            {
                // Put code here
            }

Now your code look like:

alertDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int id) 
            {
                MainActivity.this.folderName = userInput.getText().toString();
                $mkdir(curDir,folderName);
            }

        })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM