[英]Break out of a method from anonymous inner class
我有一个方法:
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();
}
事情就是这样,如果我的代码到达了ESCAPE
(也就是说,用户决定不覆盖),我想完全退出该方法。 我努力了...
someMethod()
来返回一个布尔值,然后从否定按钮返回它,但是它不允许我,因为它在内部无效的方法内。 ESCAPE
引发异常以在外部捕获,但是编译器不允许我这样做,因为DialogInterface.OnClickListener
不会引发。 break
语句离开for
循环,但这也不起作用。 简单地离开for
循环也是可以接受的。 我可以解释。 我已经尽力找到了所有可以找到的东西,但是我已经快要结束了。
您可以抛出RuntimeException或其子类之一。 编译器不会对此抱怨。
您可以使用以下方法增强代码:
// 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还具有其他方法,例如Handlers等。
当该方法执行时,您不在循环中。 它可能可以访问在那里声明的变量(如果它们是最终变量),但是一旦单击它们,OnClickListener便会执行,完全不在该循环中/从该循环中删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.