Checkboxes in AlertDialog always return the same values

4

I have AlertDialog with a custom layout with 2 checkboxes. But even if I click on one of those checkboxes, clicking on the accept or cancel buttons ( alert.setPositiveButton or alert.setNegativeButton ), I get the default checkboxes and I do not know if I clicked on them or not.

Creating AlertDialog

AlertDialog.Builder alert = new AlertDialog.Builder(novo_layout.this);
alert.setCancelable(false);
LayoutInflater inflater = this.getLayoutInflater();
alert.setView(inflater.inflate(R.layout.layout_alert, null));
alert.setMessage(IdAsString);

Checkboxes variables

View view = inflater.inflate(R.layout.layout_alert, null);
sentado = (CheckBox)view.findViewById(R.id.sentado);
livre = (CheckBox)view.findViewById(R.id.livre);

Checkboxes

alert.setPositiveButton("X", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int whichButton) {

    if(!sentado.isChecked()&&!livre.isChecked()){
         Toast.makeText(getApplicationContext(), "Os dados não foram gravados, indroduza uma posição", Toast.LENGTH_SHORT).show();
     //checkBoxClicked.setChecked(false);
    }

Whenever you do the check if(!sentado.isChecked()&&!livre.isChecked()) returns true (by default, no checkbox is clicked) even if I clicked a checkbox.

    
asked by anonymous 08.12.2016 / 13:06

1 answer

4

The problem is that the variables sentado and livre refer to the CheckBox of another View and not the one passed to AlertDialog .

alert.setView(inflater.inflate(R.layout.layout_alert, null));

In the previous code a View is inflated and passed to AlertDialog .

Then with

View view = inflater.inflate(R.layout.layout_alert, null);
sentado = (CheckBox)view.findViewById(R.id.sentado);
livre = (CheckBox)view.findViewById(R.id.livre);

You are "inflating" another View to get references to CheckBox .

What should be done is to pass the View , used to get the references, to AlertDialog .

LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.layout_alert, null);
sentado = (CheckBox)view.findViewById(R.id.sentado);
livre = (CheckBox)view.findViewById(R.id.livre);

AlertDialog.Builder alert = new AlertDialog.Builder(novo_layout.this);
alert.setCancelable(false);
alert.setView(view);
alert.setMessage(IdAsString);
    
08.12.2016 / 14:51