简体   繁体   中英

Printing multiple checkbox names only when they are checked

I have list of checkbox and want to print their names every time I click the show message button. The message appears as a android.widget.Toast. If multiple checkboxes are checked, I would like to print all of them in one string. I am using switch-case statement to determine that which checkboxes are clicked and in the cases adding the new name into my result string.

case R.id.cbox_choclate_syrup:
                if (checked)
                    tag = tag + "chocolate syrup ";
                break;

在此处输入图片说明

Here I am having issue. The result string was created at the beginning of the class and after first button hit, for the second hit it contains same item names even if they are not checked. I can add more item but the result string never get reset.

public void tosMessage(String message){
        Context context = getApplicationContext();
        CharSequence msg = message;
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, msg, duration);
        toast.show();
        // resetting the result string.
        tag = "Toppings: ";
    }

As shown above, I have tried to reset the result string at the end of onClick method which belongs to button. In this case, the previous checked items got deleted in second click even if I did not uncheck them.

public class MainActivity extends AppCompatActivity {

    public static String tag = "Toppings: ";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onCheckboxClicked(View view) {

        // is the view now checked.
        boolean checked = ((CheckBox) view).isChecked();

        // check which checkbox is checked?
        switch (view.getId()){
            case R.id.cbox_choclate_syrup:
                if (checked)
                    tag = tag + "chocolate syrup ";
                break;
            case R.id.cbox_sprinkles:
                if (checked)
                    tag = tag + "sprinkles ";
                break;
            case R.id.cbox_crushed_nuts:
                if (checked)
                    tag = tag + "crushed nuts ";
                break;
            case R.id.cbox_cherries:
                if (checked)
                    tag = tag + "cherries ";
                break;
            case R.id.cbox_orio_cookie_crumbles:
                if (checked)
                    tag = tag + "orio cookie crumbles ";
                break;
        }
    }

    public void tosMessage(String message){
        Context context = getApplicationContext();
        CharSequence msg = message;
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, msg, duration);
        toast.show();
        tag = "Toppings: ";
    }

    public void showMsg(View view) {
        tosMessage(tag);
    }
}

I expect to print only and exclusively checked item names every time I click the button. Please help me to find a solution for this.

You should first check if something was selected already, then change the String based on that. I have also changed your logic a bit.

public class MainActivity extends AppCompatActivity {

    public static String tag = "Toppings: ";

    //KEEP REFERENCE TO SELECTIONS
    boolean isCboxChoclateSyrupChecked = false;
    boolean isCboxSprinklesChecked = false;
    boolean isCboxCrushedNutsChecked = false;
    boolean isCboxCherriesChecked = false;
    boolean isCboxOrioCookieCrumblesChecked = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onCheckboxClicked(View view) {

        // is the view now checked.
        boolean checked = ((CheckBox) view).isChecked();

        // check which checkbox is checked?
        switch (view.getId()){

            case R.id.cbox_choclate_syrup:
                if (checked){
                    isCboxChoclateSyrupChecked = true;
                }else{
                    isCboxChoclateSyrupChecked = false;
                }                        
                break;

            case R.id.cbox_sprinkles:
                if (checked){
                    isCboxSprinklesChecked = true;
                }else{
                    isCboxSprinklesChecked = false;
                }                        
                break;

            case R.id.cbox_crushed_nuts:
                if (checked){
                    isCboxCrushedNutsChecked = true;
                }else{
                    isCboxCrushedNutsChecked = false;
                }
                break;

            case R.id.cbox_cherries:
                if (checked){
                    isCboxCherriesChecked = true;
                }else{
                    isCboxCherriesChecked = false;
                }
                break;

            case R.id.cbox_orio_cookie_crumbles:
                if (checked){
                    isCboxOrioCookieCrumblesChecked = true;
                }else{
                    isCboxOrioCookieCrumblesChecked = false;
                }
                break;
        }
    }

    public void tosMessage(String messageTag){
        String getAllSelected = "";

        if (isCboxChoclateSyrupChecked){
            getAllSelected = getAllSelected + "chocolate syrup ";
        }
        if (isCboxSprinklesChecked){
            getAllSelected = getAllSelected + "sprinkles ";
        }
        if (isCboxCrushedNutsChecked){
            getAllSelected = getAllSelected + "crushed nuts ";
        }
        if (isCboxCherriesChecked){
            getAllSelected = getAllSelected + "cherries ";
        }
        if (isCboxOrioCookieCrumblesChecked){
            getAllSelected = getAllSelected + "orio cookie crumbles ";

        }

        Toast toast = Toast.makeText(getApplicationContext(), messageTag+" "+getAllSelected, Toast.LENGTH_SHORT);
        toast.show();

    }

    public void showMsg(View view) {
        tosMessage(tag);
    }
}

If you selected cherries and sprinkles, your toast should show:

Toppings: cherries sprinkles

First declare checkboxes in your Java File

CheckBox cbox_choclate_syrup,cbox_sprinkles,cbox_crushed_nuts,cbox_cherries, cbox_orio_cookie_crumbles;

Then copy and paste the following functions:

private void setupFindViewById(){
    CheckBox cbox_choclate_syrup = findViewById(R.id.cbox_choclate_syrup);
    cbox_sprinkles = findViewById(R.id.cbox_sprinkles);
    cbox_crushed_nuts = findViewById(R.id.cbox_crushed_nuts);
    cbox_cherries = findViewById(R.id.cbox_cherries);
    cbox_orio_cookie_crumbles = findViewById(R.id.cbox_orio_cookie_crumbles);    
}


private CheckBox[] getCheckBoxArray(){
    return new CheckBox[]{
        CheckBox cbox_choclate_syrup,cbox_sprinkles,cbox_crushed_nuts,cbox_cherries, cbox_orio_cookie_crumbles
    }; 
}

In your onCreate method call the setupFindViewById()

now replace your onCheckboxClicked method with following:

public void onCheckboxClicked(View view) {

     tag = "Toppings: ";
     for(CheckBox checkBox: getCheckBoxArray()){
        boolean checked = checkBox.isChecked();
        switch (checkBox.getId()){
            case R.id.cbox_choclate_syrup:
                if (checked)
                    tag = tag + "chocolate syrup ";
                break;
            case R.id.cbox_sprinkles:
                if (checked)
                    tag = tag + "sprinkles ";
                break;
            case R.id.cbox_crushed_nuts:
                if (checked)
                    tag = tag + "crushed nuts ";
                break;
            case R.id.cbox_cherries:
                if (checked)
                    tag = tag + "cherries ";
                break;
            case R.id.cbox_orio_cookie_crumbles:
                if (checked)
                    tag = tag + "orio cookie crumbles ";
                break;
        }
     }
}

Now you are good to go:

What I've done: First we needed variables corresponding to your widgets. Then we created a function getCheckBoxArray() this will return an array of checkboxes. In onCheckboxClicked method, we loop through the array because we want to check the state of each checkbox


The issue mentioned in comment :

However, it doesn't work on the second button click. Let me explain; when I select cherries and sprinkles and click the show message button, the toast appears perfectly with two toppings that I selected with the checkboxes. But without any chain on checkboxes (all checkboxes remains same as the first click) and do the second click on the button, the toast appears empty. I think I need a way to reset my tag but where?

This is happening because the value of the tag variable is set to tag = "Toppings: ";
in tosMessage(String message) method. If you remove that line from this method then it should work fine.

When view.getId() equals to one of the cases, the statement in that case runs and break terminates the whole switch-case so the application doesn't check other CkeckBox s. So you have to replace switch statement with an if-else-if .

int id= view.getId();
if(id == R.id.cbox_choclate_syrup){
    if(checked)
        tag = tag + "chocolate syrup ";
}
else if(id == R.id.cbox_sprinkles){
    if(checked)
        tag = tag + "sprinkles ";
}
else if(id == R.id.cbox_crushed_nuts){
    if(checked)
        tag = tag + "crushed nuts ";
}
else if(id == R.id.cbox_cherries){
    if(checked)
        tag = tag + "cherries ";
}
else if(id == R.id.cbox_orio_cookie_crumbles){
    if(checked)
        tag = tag + "orio cookie crumbles ";
}

Note: deleting break statements won't work.

Declare ch1,ch2,ch3,ch4,ch5 as Checkbox . And message as a private and global String , assign its value to "Toppings:" .

CheckBox ch1,ch2,ch3,ch4,ch5;
private String message = "Toppings: ";

In onCraete method get reference of ch1,ch2,ch3,ch4,ch5 by findViewById().

    ch1 = findViewById(R.id.checkBox_chocolate_syrup);
    ch2 = findViewById(R.id.checkBox_sprinkles);
    ch3 = findViewById(R.id.checkBox_crushed_nuts);
    ch4 = findViewById(R.id.checkBox_cherries);
    ch5 = findViewById(R.id.checkBox_orio_cookie);

Create a custom method named showToast().

public void showToast () {

    if (ch1.isChecked()) {
            message += ch1.getText().toString() + " ";
        }
        if (ch2.isChecked()) {
            message += ch2.getText().toString() + " ";
        }
        if (ch3.isChecked()) {
            message += ch3.getText().toString() + " ";
        }
        if (ch4.isChecked()) {
            message += ch4.getText().toString() + " ";
        }
        if (ch5.isChecked()) {
            message += ch5.getText().toString() + " ";
        }

        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

We defined displayToast() another method as a value of android:onClick attribute to show toast by Button click. Now we will call showToast () method from it to show toast and then we will reset message String to prepare for next click.

public void displayToast(View view) {
    showToast();
    message = "Toppings: ";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM