Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well, I was going to say that I am very pleased with myself because I found a simple answer, all by myself!<br> But the truth is that although I find a way to return a value (which I show below). <strong>It is of no use</strong>.</p> <p>The real problem is I wanted a synchronous Dialog, a dialog that waits for the user to answer before resuming your code after <code>dialog.show()</code>.<br> <strong>There is no such beast in Android</strong>. All dialogs are asynchronous, so <code>dialog.show()</code> only posts the dialog in some queue (I think) and continues. Thus you don't get your answer in time.</p> <p>For all its worth (nothing) below you'll find how to set a value inside the method that builds the dialog. Maybe there are other uses for this technique, not related to the dialog lifecycle.</p> <p><br><br><br></p> <p>To give some related info, I'll say that if you replace</p> <pre class="lang-js prettyprint-override"><code>boolean answer; </code></pre> <p>with</p> <pre class="lang-js prettyprint-override"><code>final boolean answer; </code></pre> <p>it is possible to access the variable from within the listener, but it is not possible to assign it a new value, since it was declared as <strong>final</strong>.</p> <p>Here comes the trick.<br> Define the variable as:</p> <pre class="lang-js prettyprint-override"><code>final boolean[] answer = new boolean[1]; </code></pre> <p>Some of you already see why this will work. The final variable here is not the single element of the boolean array, is the array itself.<br> So now you can assign the array element [0] as you wish.</p> <pre class="lang-js prettyprint-override"><code>dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int buttonId) { answer[0] = true; } }); . . . return answer[0]; </code></pre> <p>And finally you can return it from your method.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload