mardi 6 janvier 2015

AlertDialog selection cancels onCheckedListener for CheckBox

I have an onCheckedListener on a CheckBox. When the checkbox is clicked, an AlertDialog popup appears with two options: "Mark as incomplete/complete" which checks/unchecks the box. This works fine. The other options is "Remove from Plan" which will then prompt the user with another AlertDialog to "Confirm" or "Cancel" the remove. When I chose "Cancel" it exits out of both AlertDialogs and goes back to the main activity. After that, when I click on the CheckBox again, the initial AlertDialog does not show back up. I'm not sure what I'm doing wrong here. Here is the code:



package com.example.testcheckbox;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class MainActivity extends ActionBarActivity {

private CheckBox cb;
boolean isShowing = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb = (CheckBox) findViewById(R.id.checkbox);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
final boolean isChecked) {
if (!isShowing) {
isShowing = true;
CharSequence options[];
if (isChecked) {
cb.setChecked(false);
options = new CharSequence[] { "Mark as Complete",
"Remove from Plan"};
} else {
cb.setChecked(true);
options = new CharSequence[] {
"Mark as Incomplete", "Remove from Plan"};
}
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setItems(options,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {

switch (which) {
case 0:
cb.toggle();
dialog.cancel();
break;
case 1:
AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(
MainActivity.this);

confirmBuilder
.setMessage(
"Are you sure you want to remove this task from your plan?")
.setCancelable(false)
.setPositiveButton(
"Confirm",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
cb.setVisibility(View.GONE);
dialog.cancel();
}
})
.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
dialog.cancel();
}
});

// create alert dialog
AlertDialog alertDialog = confirmBuilder
.create();

// show it
alertDialog.show();
break;
}

}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
isShowing = false;
}
});
builder.show();
}
}
});
}
}


Any ideas on why the listener stops working after I bring up my second AlertDialog?





Aucun commentaire:

Enregistrer un commentaire