How do you sort Actors in a libgdx Stage?
Rather than the accepted answer, I like it better to prepare several "layer" groups, then adding to those group in whatever order it pleases me.
Group bg = new Group();
Group fg = new Group();
// the order is important in the following two lines
stage.addActor(bg);
stage.addActor(fg);
bg.addActor(whatever);
fg.addActor(whatever);
bg.addActor(whatever);
fg.addActor(whatever);
(Of course the addActor()
order still matters among elements of bg
, and among elements of fg
, but not between an element of fg
and an element of bg
.)
This workflow works well in an inheritance scenario, where the base class owns protected Group layers (this.bg
, this.fg
, ...) and adds them in order to the stage. Then the derived class can add things to those layers without taking care of the order.
Looks like your code Stage.getActors()
returns an Array
of Actors
instead of a List
.
Collections.sort()
method accepts only Lists.
Try:
Collections.sort(Arrays.asList(Stage.getActors().toArray()), new ActorComparator());
Update on sorting (by z-index in the question) from @James Holloway: z-index is overridden by the stage to be whatever the internal order of the Array is. So setting the Z-Index has no effect, except in the case that you set it as higher than the length of the list and then it just puts the image on top of the list (internal Stage does this). This is solved by sorting by name or ID.