nex3z / ToggleButtonGroup

A group of flowable toggle buttons, with multiple / single selection support and button customization.
Apache License 2.0
421 stars 49 forks source link

Set ToggleButton to Checked state by the string text? #41

Closed ghost closed 5 years ago

ghost commented 5 years ago

Actually I am using your library to let the user select their "Interests", I am programmatically creating the interests and save the selected one on server as strings, then when a user logs in I get his interests as strings, I just want to know how can I set checked on those buttons which user has selected using the string values? Thanks a lot for your help!

nex3z commented 5 years ago

For a straight forward solution, you can iterate through all the selected interests and all the buttons, check the button if its text matches the selected interest.

String[] selectedInterests = {"Hiking", "Skiing"}; // These are the seleced interests you get from server
for (int i = 0; i < interestsMultiSelectToggleGroup.getChildCount(); i++) { // Iterate through all the button in the toggle group
    LabelToggle toggle = (LabelToggle) interestsMultiSelectToggleGroup.getChildAt(i);
    for (String selected : selectedInterests) { // Iterate through all the selected interests to find a match
        if (toggle.getText().equals(selected)) {
            toggle.setChecked(true);
        }
    }
}

device-2018-10-06-222238

This works if the total number of interests is small, that iterate through all the interests is cheap.

If you have many interests, you'd better use some kind of Map to map interest string to the corresponding button (or its position in the toggle group), so that you can get the button by interest text much more efficiently.

ghost commented 5 years ago

Thanks a lot Man, believe me You are the Best.