Search code examples
javauser-interfacelibgdxscene2d

Libgdx How to implement list of checked buttons?


How can I implement a list of horizontally aligned buttons in which only one button can be checked at a moment? I wanted to implement this for a game in which you have to select the tool from a list and click on an object to perform an action. I want to highlight the button which represents the current tool and when you choose another one to return the previous one to the non-highlighted state and the one that has been chosen to the highlighted state. So there can be only one tool active at any given moment and also after you used the tool and didn't select something else there should be no highlighted button. I tried the past two days to implemented it myself but I couldn't do it. I thought that maybe there is something like this in libgdx scene2d but I didn't find anything. Any help or advice would be appreciated.


Solution

  • Sounds like a job for a ButtonGroup. I'm surprised that didn't show up after a basic google search.

    See the answer here: LibGDX: Make all actors on a stage unchecked

    //initalize stage and all your buttons
    ButtonGroup buttonGroup = new ButtonGroup(button1, button2, button3, etc...)
    //next set the max and min amount to be checked
    buttonGroup.setMaxCheckCount(1);
    buttonGroup.setMinCheckCount(0);
    //it may be useful to use this method:
    buttonGroup.setUncheckLast(true); //If true, when the maximum number of buttons are checked and an additional button is checked, the last button to be checked is unchecked so that the maximum is not exceeded.