2
\$\begingroup\$

Recently I wanted to use libGDX's Table to show four buttons. But my table doesn't fit on the stage:

enter image description here

Here is the code I used:

table.add(new GameButton("1"));
table.add(new GameButton("2"));
table.add(new GameButton("3"));
table.add(new GameButton("4"));
table.align(Align.bottom);
table.setFillParent(true);
stage.addActor(table);

(GameButton is a TextButton subclass with a special TextButtonStyle.)

When I change table.add(new GameButton("1")); to table.add(new GameButton("1")).width(Gdx.graphics.getWidth() / 4);

I get this result: enter image description here

Does Table (or another libGDX layout class) have functionality to auto-fit elements like in the second picture? Or I should always add some width/height options after adding element?

\$\endgroup\$
0
\$\begingroup\$

You probably want to check out the fillX() (and fillY()) methods on the table, documented here.

The fill methods cause a widget to be sized to the cell subject to the minimum and maximum size constraints of the widget itself. You'd probably want to do something like table.add(new GameButton("1")).expand().bottom().fillX();

\$\endgroup\$
  • \$\begingroup\$ I tried your version and here's result: link. As you can see, right button is bigger than other, and all buttons overlap each other. So it doesn't look nice. \$\endgroup\$ – OneOne Dec 15 '15 at 16:59
  • \$\begingroup\$ I'd guess that has to do with your minimum size constraints on the button type (or with the expand call, which you may not need depending on the other style properties set). \$\endgroup\$ – user1430 Dec 15 '15 at 17:00
0
\$\begingroup\$

Got it!

As Josh Petrie said, we should use .expand().fillX() after adding each button. After that we should override getMinWidth() method for GameButton class (for example, with return 0). As result, you get correct layout!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.