L chowney L chowney - 1 month ago 9
Android Question

how can I made a switch case into a for each loop - android studio

Here i have a switch case for 3 choices on a dialog single choice.
At the moment i have 3 items in my sequence but this isnt what im intending im wanting alot more I want to add 25 choices and I dont think its good coding to have 24 cases (including 0) how can i replicate what ive done in a for each loop?

public class Multiselection extends DialogFragment {

final CharSequence[] items={"easy","medium","hard"};
String selection;
@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final String [] items = getResources().getStringArray(R.array.my_drinks_selection); //gets array items to screen
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose drink").setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

switch (which) {
case 0:
selection = (String) items[which];

break;
case 1:
selection = (String) items[which];

break;
case 2:
selection = (String) items[which];

break;
}

}

Answer
public class Multiselection extends DialogFragment {

final CharSequence[] items={"easy","medium","hard"};
String selection;
@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final String [] items = getResources().getStringArray(R.array.my_drinks_selection); //gets array items to screen
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose drink").setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        selection = items[which];
    }
}
Comments