嘗試在 onClick 監聽器中直接修改局部變量 boolean answer 並返回,**不可行**,因為:
final,無法重新賦值。dialog.show() 是**異步**的,不會阻塞當前線程,方法會立即返回默認值。public interface ConfirmCallback {
void onResult(boolean confirmed);
}
public static void confirm(Context context, ConfirmCallback callback) {
new AlertDialog.Builder(context)
.setTitle("確認")
.setMessage("是否繼續?")
.setPositiveButton("是", (d, w) -> callback.onResult(true))
.setNegativeButton("否", (d, w) -> callback.onResult(false))
.setCancelable(false)
.show();
}
// 調用
confirm(this, confirmed -> {
if (confirmed) {
// 用戶點擊是
} else {
// 用戶點擊否
}
});
可用 CountDownLatch 配合 final boolean[] answer = new boolean[1] 實現,但**嚴禁在主線程使用**,否則導致 ANR。