dimanche 1 novembre 2015

how to set a method only if a checkbox is selected?

That's a tricky one.

I have two checkboxes and I would like to attach some text to a string depending on whether the checkboxes are clicked. E.G. if checkbox1 is clicked, it adds "A" to the string "result" if checkbox2 is clicked, it adds "B" to the string "result"

I tried several different methods and apparently the closest one is onClick.

final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox);
    checkBox1.setChecked(false);

    checkBox1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (checkBox1.isChecked()) {
                builder.append(value1).append("\n");
                Toast.makeText(MainActivity.this, "item selected", Toast.LENGTH_LONG).show();
            }
            else {
                builder.append("");
            }
        }
    });

    final CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
    checkBox2.setChecked(false);

    checkBox2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (checkBox2.isChecked()) {
                builder.append(value2).append("\n");
                Toast.makeText(MainActivity.this, "item selected", Toast.LENGTH_LONG).show();
            } else {
                builder.append("");
            }
        }
    });

I tried also the onChangedState or something like that, but it does not work for my purpose.

Following a normal behaviour, if I click once, I append "A" and if click twice, I append "". Yet, if I click three times, I append "A" "A", and not only "A".

Any idea on how to address this nuisance? probably some true/false statement?




Aucun commentaire:

Enregistrer un commentaire