lundi 2 novembre 2015

delete method on StringBuilder

I have a tricky question.

I have various CheckBoxes and when I click on one, I am appending some text to a String through the StringBuilder method. Likewise, I want the given text to be deleted, when the checkbox is unticked.

The problem is, I can't use the builder.delete because the text I am adding is a variable String.

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

    checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (checkBox1.isChecked()) {
                builder.append(value1).append("\n");
                Toast.makeText(MainActivity.this, "item selected", Toast.LENGTH_LONG).show();
            }
            else{
                builder.setLength(builder.length() - 4);
            }
        }
    });

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

    checkBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (checkBox2.isChecked()) {
                builder.append(value2).append("\n");
                Toast.makeText(MainActivity.this, "item selected", Toast.LENGTH_LONG).show();
            }
            else{
                builder.setLength(builder.length() - 5);
            }
        }
    });

As you can see, I am adding the strings "Value1" and "Value2" which could be 1 or 30 digits long (hence why the setLength method does not work).

Moreover, if I click on checkbox1 and then on checkbox2 and, say, I want to unflag Checkbox1, Android would remove the text obtained from checkbox2.

I tried also the replace, but it didn't go well for no reasons

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

    checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (checkBox1.isChecked()) {
                builder.append(value1).append("\n");
                Toast.makeText(MainActivity.this, "item selected", Toast.LENGTH_LONG).show();
            }
            else{
                String replaceString;
                replaceString = builder.replace(value1, " ");
                System.out.println(replaceString);
            }
        }
    });

I would like a direct way to tackle the string I have added and delete it!




Aucun commentaire:

Enregistrer un commentaire