Search code examples
libgdxscene2d

Using one ButtonStyle for more than one Button[Libgdx Scene2d]


I'm making an interface using Libgdx Scene2d, and I have more than one button which all require different style, this means I have to create one buttonStyle for each button?

        btnStyle = new TextButton.TextButtonStyle();
        btnStyle.up = btnSkin.getDrawable("boxBtn");
        btnStyle.checked = btnSkin.getDrawable("boxBtn1");

        btnBox = new Button(btnStyle);

        anotherButton = new Button(newStyle?) //this is what I mean

Solution

  • Your thinking is correct. For each button that requires a different style, you will need a different TextButtonStyle.

    TextButtonStyle styleOne = new TextButtonStyle();
    styleOne.up = ...someDrawable1
    
    TextButtonStyle styleTwo = new TextButtonStyle();
    styleTwo.up = ...someDrawable2
    
    TextButton button1 = new TextButton("Button1", styleOne);
    TextButton button2 = new TextButton("Button2", styleTwo);
    

    If you find that you are using the same set of styles over and over again, you could create static styles and use those for your buttons.

    public class Styles {
        public static final TextButtonStyle styleOne = new TextButtonStyle();
        public static final TextButtonStyle styleTwo = new TextButtonStyle();
    
        public static void initStyles() {
             styleOne.up = ...
    
             styleTwo.up = ....
        }
    }
    

    Then call Styles.initStyles() when you've loaded your assets.

    If you want to customize each style, but still use a set of default style attributes, you could try something like this:

    public class Styles {
    
        public static TextButtonStyle createTextButtonStyle(Drawable up, Drawable down) {
            TextButtonStyle style = new TextButtonStyle();
            style.up = up;
            style.down = down;
            style.font = Assets.getDefaultFont() //For example
            style.fontColor = Assets.getDefaultFontColor() //For example
        }
    }
    

    Then when you want to create a button, you can just do:

    TextButton button = new TextButton("Text", Styles.createTextButtonStyle(drawable1, drawable2));
    

    Hope this helps clear some things up.