Search code examples
javaandroidradio-buttontoast

Passing multiple values to Toast


I have been trying to make a small application to learn android development, I have set up 4 radio buttons each representing a different color. My problem is that I cannot find a way to pass the values from the radio buttons to the toast if the user selects them, for example if the user selects yellow and blue the toast would output that the user had selected the colors blue and yellow, I can only find documentation to pass one value to the toast.

How to over come this?

chooseColor.setOnClickListener(new View.OnClickListener()
{

    @Override
    public void onClick(View v) 
    {
        blue = (RadioButton) findViewById(selectedId);
        red = (RadioButton) findViewById(selectedId);
        yellow = (RadioButton) findViewById(selectedId);
        green = (RadioButton) findViewById(selectedId);
        brown = (RadioButton) findViewById(selectedId);

        Toast toast = Toast.makeText(getApplicationContext(), 
        blue.getText(), Toast.LENGTH_SHORT);            
        toast.setGravity(Gravity.CENTER|Gravity.CENTER_HORIZONTAL, 0, 0);                   
        toast.show();
    }
});

Solution

  • You can only pass a single String to Toast.makeText() to be displayed in the Toast. However, you can easily build up a String with all the information that you desire by using + to concatenate Strings together or a StringBuilder to create one more dynamically.

    As a side note, your current code will show "Blue" whether or not the blue radio button is selected. You will need several if statements to determine which radio buttons are selected.