问题
I have a method:
void someMethod(String someString)
final String[] testAgainst = {...};
....
for(int i = 0; i < testAgainst.length; i++) {
if (someString.equals(testAgainst[i])) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Strings are the same! Overwrite?")
.setTitle("Blah Blah Blah")
.setCancelable(false)
.setPositiveButton("Overwrite", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int which) {
someAction()
}
})
.setNegativeButton("Nah", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int which) {
ESCAPE
}
});
AlertDialog dialog = builder.create();
}
}
doSomeOtherStuff();
}
Here's the thing, if my code reaches ESCAPE
(that is, the user decides not to overwrite), I want to exit the method completely. I have tried...
- changing
someMethod()
to return a boolean, then returning it from the negative button, but it won't let me because it's within a void internal method. - throwing an exception from
ESCAPE
to be caught externally, but the compiler won't let me becauseDialogInterface.OnClickListener
doesn't throw. - using a
break
statement to leave thefor
loop, but that doesn't work either.
It would also be acceptable to simply leave the for
loop. I can account for that. I've tried everything I can find and I'm at my wit's end.
回答1:
You can throw a RuntimeException or one of its subclasses. The compiler won't complain about it.
回答2:
You are not in the loop when that method executes. It may have access to the variables declared there (if they are final), but the OnClickListener is executed once they click, completely outside of/removed from that loop.
回答3:
You could enhance your code with:
// Static class that contains nothing but a trigger to exit the loop
static class Cancel { boolean shouldCancel = false; }
void someMethod(String someString)
final String[] testAgainst = {...};
....
// Initialize it `final`, else it won't be accessible inside
final Cancel trigger = new Cancel();
// Add the check as additional condition for the `for` condition
for(int i = 0; i < testAgainst.length && !trigger.shouldCancel; i++) {
if (someString.equals(testAgainst[i])) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Strings are the same! Overwrite?")
.setTitle("Blah Blah Blah")
.setCancelable(false)
.setPositiveButton("Overwrite", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int which) {
someAction()
}
.setNegativeButton("Nah", new DialongInterface.OnClickListener() {
public void onClick(DialogInterface di, int which) {
// Use the trigger to communicate back that it's time to finish
trigger.shouldCancel = true;
}
AlertDialog dialog = builder.create();
}
}
doSomeOtherStuff();
}
Android has other methods of doing that too, like Handlers etc.
来源:https://stackoverflow.com/questions/9678381/break-out-of-a-method-from-anonymous-inner-class