我有一个按钮,可以打开AlertDialog。然后,它开始倒计时,并在对话框内刷新文本:
private void countDown(int cooldown) {
countDownTimer = new CountDownTimer(cooldown, COOLDOWN_TIME_STEP_MILLIS) { //sec , steps
public void onTick(long millisUntilFinished) {
isTimerActive = false;
if (mFingerprintText != null) {
updateDialogText("Awsome text count: " + millisUntilFinished / COOLDOWN_TIME_STEP_MILLIS + " segs", false);
}
}
public void onFinish() {
isTimerActive = false;
if (mFingerprintText != null) {
updateDialogText("Awsome text count finished", false);
}
}
}.start();
}
但是,如果用户关闭拨号盘并再次打开它,我想在过去的时间内继续倒计时。我的意思是,如果我在13:00:00开始倒计时(计数1分钟),并且用户在13:00:15关闭,如果用户再次打开,例如在13:00:30,我想要继续计数,所以在这个时刻反击仍需要再计数30秒......
我尝试了一些不同的方法,但我没有实现它。
private void showTimerDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_request_android_timer, null);
builder.setView(dialogView);
if (!isTimerActive) {
mTimerText = (TextView) dialogView.findViewById(R.id.dialog_timer_text);
}
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (mActive) {
deactivate();
}
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
mDialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mDialog.dismiss();
}
});
mDialog = builder.create();
mDialog.setCanceledOnTouchOutside(false);
mDialog.show();
}
答案 0 :(得分:1)
不要在本地创建Dialog对象。在Activity中创建一个全局变量。现在,您的对话框创建和解雇可以是我们或方法showTimerDialog
覆盖Dialog的AlertDialog.BUTTON_POSITIVE
和AlertDialog.BUTTON_NEGATIVE
.Call类方法来处理这些场景
public class StartRaceFrag extends Activity{
//Keep a global instance
private AlertDialog mDialog;
//Create a boolean to check if timer already started or not
private boolean isTimerstarted;
现在在方法创建对象并按下对话框
private void showTimerDialog(Context context) {
//Start timer based on this bool variable
if(!isTimerstarted){
isTimerstarted=true;
}
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_request_android_timer, null);
builder.setView(dialogView);
mDialog=builder.create();
//Other dialog related statements
//Override the Dialog Positive and Negative button and call other class methods to handle
现在基于这个bool变量,您可以修改方法来运行计时器
private void countDown(int cooldown) {
if(isTimerstarted){
// Your business logic
}else{
//Handle for else case
}
}