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.
Aucun commentaire:
Enregistrer un commentaire