-
Notifications
You must be signed in to change notification settings - Fork 433
Animations
There are many ways to animate and liven the data within a Codename One application, layout animations are probably chief among them. But first we need to understand some basics such as layout reflows.
Layout in tools such as HTML is implicit, when you add something into the UI it is automatically placed correctly. Other tools such as Codename One use explicit layout, that means you have to explicitly request the UI to layout itself after making changes!
|
Important
|
Like many such rules exceptions occur. E.g. if the device is rotated or window size changes a layout will occur automatically. |
When adding a component to a UI that is already visible, the component will not show by default.
|
Tip
|
When adding a component to a form which isn’t shown on the screen, there is no need to tell the UI to repaint or reflow. This happens implicitly. |
The chief advantage of explicit layout is performance.
E.g. imagine adding 100 components to a form. If the form was laid out automatically, layout would have happened 100 times instead of once when adding was finished. In fact layout reflows are often considered the #1 performance issue for HTML/JavaScript applications.
|
Note
|
Smart layout reflow logic can alleviate some of the pains of the automatic layout reflows however since the process is implicit it’s almost impossible to optimize complex usages across browsers/devices. A major JavaScript performance tip is to use absolute positioning which is akin to not using layouts at all! |
That is why, when you add components to a form that is already showing, you should invoke revalidate or animate the layout appropriately. This also enables the layout animation behavior explained below.
To understand animations you need to understand a couple of things about Codename One components. When we add a component to a container, it’s generally just added but not positioned anywhere. A novice might notice the setX/setY/setWidth/setHeight methods on a component and just try to position it absolutely.
This won’t work since these methods are meant for the layout manager, which is implicitly invoked when a form is shown (internally in Codename One), and the layout manager uses these methods to position/size the components based on the hints given to it.
If you add components to a form that is currently showing, it is your responsibility to invoke revalidate/layoutContainer to arrange the newly added components (see Layout Reflows).
animateLayout() method is a fancy form of revalidate that animates the components into their laid out position. After changing the layout & invoking this method the components move to their new sizes/positions seamlessly.
This sort of behavior creates a special case where setting the size/position makes sense. When we set the size/position in the demo code here we are positioning the components at the animation start position above the frame.
Form hi = new Form("Layout Animations", new BoxLayout(BoxLayout.Y_AXIS));
Button fall = new Button("Fall");
fall.addActionListener((e) -> {
for(int iter = 0 ; iter < 10 ; iter++) {
Label b = new Label ("Label " + iter);
b.setWidth(fall.getWidth());
b.setHeight(fall.getHeight());
b.setY(-fall.getHeight());
hi.add(b);
}
hi.getContentPane().animateLayout(20000);
});
hi.add(fall);This results in:

There are a couple of things that you should notice about this example:
-
We used
hi.getContentPane().animateLayout(20000);& nothi.animateLayout(20000);. You need to animate the "actual" container andFormis a special case. -
We used a button to do the animation rather than doing it on show. Since
show()implicitly lays out the components it wouldn’t have worked correctly.
While layout animations are really powerful effects for adding elements into the UI and drawing attention to them. The inverse of removing an element from the UI is often more important. E.g. when we delete or remove an element we want to animate it out.
Layout animations don’t really do that since they will try to bring the animated item into place. What we want is the exact opposite of a layout animation and that is the "unlayout animation".
The "unlayout animation" takes a valid laid out state and shifts the components to an invalid state that we defined in advance. E.g. we can fix the example above to flip the "fall" button into a "rise" button when the buttons come into place and this will allow the buttons to float back up to where they came from in the exact reverse order.
|
Warning
|
An unlayout animation always leaves the container in an invalidated state. |
Form hi = new Form("Layout Animations", new BoxLayout(BoxLayout.Y_AXIS));
Button fall = new Button("Fall");
fall.addActionListener((e) -> {
if(hi.getContentPane().getComponentCount() == 1) {
fall.setText("Rise");
for(int iter = 0 ; iter < 10 ; iter++) {
Label b = new Label ("Label " + iter);
b.setWidth(fall.getWidth());
b.setHeight(fall.getHeight());
b.setY(-fall.getHeight());
hi.add(b);
}
hi.getContentPane().animateLayout(20000);
} else {
fall.setText("Fall");
for(int iter = 1 ; iter < hi.getContentPane().getComponentCount() ; iter++) {
Component c = hi.getContentPane().getComponentAt(iter);
c.setY(-fall.getHeight());
}
hi.getContentPane().animateUnlayoutAndWait(20000, 255);
hi.removeAll();
hi.add(fall);
hi.revalidate();
}
});
hi.add(fall);You will notice some similarities with the unlayout animation but the differences represent the exact opposite of the layout animation:
-
We loop over existing components (not newly created ones)
-
We set the desired end position not the desired starting position
-
After the animation completes we need to actually remove the elements since the UI is now in an invalid position with elements outside of the screen but still physically there!
-
We used the
AndWaitvariant of the animate unlayout call. We could have used the async call as well.
Most animations have two or three variants:
-
Standard animation e.g.
animateLayout(int) -
And wait variant e.g.
animateLayoutAndWait(int) -
Callback variant e.g.
animateUnlayout(int, int, Runnable)
The standard animation is invoked when we don’t care about the completion of the animation. We can do this for a standard animation.
|
Note
|
The unlayout animations don’t have a standard variant. Since they leave the UI in an invalid state we must always do something once the animation completes so a standard variant makes no sense |
The AndWait variant blocks the calling thread until the animation completes. This is really useful for sequencing animations one after the other e.g this code from the kitchen sink demo:
arrangeForInterlace(effects);
effects.animateUnlayoutAndWait(800, 20);
effects.animateLayoutFade(800, 20);First the UI goes thru an "unlayout" animation, once that completes the layout itself is performed.
|
Important
|
The AndWait calls needs to be invoked on the Event Dispatch Thread despite being "blocking". This is a common convention in Codename One powered by a unique capability of Codename One: invokeAndBlock.You can learn more about invokeAndBlock in the
EDT section.
|
The callback variant is similar to the invokeAndBlock variant but uses a more conventional callback semantic which is more familiar to some developers. It accepts a Runnable callback that will be invoked after the fact. E.g. we can change the unlayout call from before to use the callback semantics as such:
hi.getContentPane().animateUnlayout(20000, 255, () -> {
hi.removeAll();
hi.add(fall);
hi.revalidate();
});There are several additional variations on the standard animate methods. Several methods accept a numeric fade argument. This is useful to fade out an element in an "unlayout" operation or fade in a regular animation.
The value for the fade argument is a number between 0 and 255 where 0 represents full transparency and 255 represents full opacity.
Some animate layout methods are hierarchy based. They work just like the regular animateLayout methods but recurse into the entire Container hierarchy. These methods work well when you have components in a nested hierarchy that need to animate into place. This is demonstrated in the opening sequence of the kitchen sink demo:
for(int iter = 0 ; iter < demoComponents.size() ; iter++) {
Component cmp = (Component)demoComponents.elementAt(iter);
if(iter < componentsPerRow) {
cmp.setX(-cmp.getWidth());
} else {
if(iter < componentsPerRow * 2) {
cmp.setX(dw);
} else {
cmp.setX(-cmp.getWidth());
}
}
}
boxContainer.setShouldCalcPreferredSize(true);
boxContainer.animateHierarchyFade(3000, 30);The demoComponents Vector contains components from separate containers and this code would not work with a simple animate layout.
|
Warning
|
We normally recommend avoiding the hierarchy version. Its slower but more importantly, it’s flaky. Since the size/position of the Container might be affected by the layout the animation could get clipped and skip. These are very hard to detect issues.
|
All the animations go thru a per-form queue: the AnimationManager. This effectively prevents two animations from mutating the UI in parallel so we won’t have collisions between two conflicting sides. Things get more interesting when we try to do something like this:
cnt.add(myButton);
int componentCount = cnt.getComponentCount();
cnt.animateLayout(300);
cnt.removeComponent(myButton);
if(componentCount == cnt.getComponentCount()) {
// this will happen...
}The reason this happens is that the second remove gets postponed to the end of the animation so it won’t break the animation. This works for remove and add operations on a Container as well as other animations.
The simple yet problematic fix would be:
cnt.add(myButton);
int componentCount = cnt.getComponentCount();
cnt.animateLayoutAndWait(300);
cnt.removeComponent(myButton);
if(componentCount == cnt.getComponentCount()) {
// this probably won't happen...
}So why that might still fail?
Events come in constantly during the run of the EDT [1], so an event might come in that might trigger an animation in your code. Even if you are on the EDT keep in mind that you don’t actually block it and an event might come in.
In those cases an animation might start and you might be unaware of that animation and it might still be in action when you expect remove to work.
AnimationManager has builtin support to fix this exact issue.
We can flush the animation queue and run synchronously after all the animations finished and before new ones come in by using something like this:
cnt.add(myButton);
int componentCount = cnt.getComponentCount();
cnt.animateLayout(300);
cnt.getAnimationManager().flushAnimation(() -> {
cnt.removeComponent(myButton);
if(componentCount == cnt.getComponentCount()) {
// this shouldn't happen...
}
}To understand the flow of animations in Codename One we can start by discussing the underlying low-level animations and the motivations behind them. The Codename One event dispatch thread has a special animation “pulse” allowing an animation to update its state and draw itself. Code can make use of this pulse to implement repetitive polling tasks that have very little to do with drawing.
This is helpful since the callback will always occur on the event dispatch thread.
Every component in Codename One contains an animate() method that returns a boolean value, you can also implement the Animation interface in an arbitrary component to implement your own animation. In order to receive animation events you need to register yourself within the parent form, it is the responsibility of the parent for to call animate().
If the animate method returns true then the animation will be painted. It is important to deregister animations when they aren’t needed to conserve battery life. However, if you derive from a component, which has its own animation logic you might damage its animation behavior by deregistering it, so tread gently with the low level API’s.
myForm.registerAnimated(this);
private int spinValue;
public boolean animate() {
if(userStatusPending) {
spinValue++;
super.animate();
return true;
}
return super.animate();
}Transitions allow us to replace one component with another, most typically forms or dialogs are replaced with a transition however a transition can be applied to replace any arbitrary component.
Developers can implement their own custom transition and install it to components by deriving the transition class, although most commonly the built in CommonTransition class is used for almost everything.
You can define transitions for forms/dialogs/menus globally either via the theme constant or via the LookAndFeel class. Alternatively you can install a transition on top-level components via setter methods.
To apply a transition to a component we can just use the Container.replace method as such:
Container c = replace.getParent();
ta.setPreferredSize(replace.getPreferredSize());
c.replaceAndWait(replace, ta, CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, true, 500));
c.replaceAndWait(ta, replace, CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, false, 500));
Codename One supports a FlipTransition that allows flipping the component or form in place in a pseudo 3D approach (see Flip Transition).
Android’s material design has a morphing effect where an element from the previous form (activity) animates into a different component on a new activity. Codename One has a morph effect in the Container class but it doesn’t work as a transition between forms and doesn’t allow for multiple separate components to transition at once.
To support this behavior we have the MorphTransition class that provides this same effect coupled with a fade to the rest of the UI (see Morph Transition).
Since the transition is created before the form exists we can’t reference explicit components within the form
when creating the morph transition (in order to indicate which component becomes which) so we need to refer
to them by name. This means we need to use setName(String) on the components in the source/destination
forms so the transition will be able to find them.
Form demoForm = new Form(currentDemo.getDisplayName());
demoForm.setScrollable(false);
demoForm.setLayout(new BorderLayout());
Label demoLabel = new Label(currentDemo.getDisplayName());
demoLabel.setIcon(currentDemo.getDemoIcon());
demoLabel.setName("DemoLabel");
demoForm.addComponent(BorderLayout.NORTH, demoLabel);
demoForm.addComponent(BorderLayout.CENTER, wrapInShelves(n));
....
demoForm.setBackCommand(backCommand);
demoForm.setTransitionOutAnimator(MorphTransition.create(3000).morph(currentDemo.getDisplayName(), "DemoLabel"));
f.setTransitionOutAnimator(MorphTransition.create(3000).morph(currentDemo.getDisplayName(), "DemoLabel"));
demoForm.show();In addition we can implement our own transitions, e.g. the following code demonstrates an explosion transition in which an explosion animation is displayed on every component as the explode one by one while we move from one screen to the next.
public class ExplosionTransition extends Transition {
private int duration;
private Image[] explosions;
private Motion anim;
private Class[] classes;
private boolean done;
private int[] locationX;
private int[] locationY;
private Vector components;
private Vector sequence;
private boolean sequential;
private int seqLocation;
public ExplosionTransition(int duration, Class[] classes, boolean sequential) {
this.duration = duration;
this.classes = classes;
this.sequential = sequential;
}
public void initTransition() {
try {
explosions = new Image[] {
Image.createImage("/explosion1.png"),
Image.createImage("/explosion2.png"),
Image.createImage("/explosion3.png"),
Image.createImage("/explosion4.png"),
Image.createImage("/explosion5.png"),
Image.createImage("/explosion6.png"),
Image.createImage("/explosion7.png"),
Image.createImage("/explosion8.png")
};
done = false;
Container c = (Container)getSource();
components = new Vector();
addComponentsOfClasses(c, components);
if(components.size() == 0) {
return;
}
locationX = new int[components.size()];
locationY = new int[components.size()];
int w = explosions[0].getWidth();
int h = explosions[0].getHeight();
for(int iter = 0 ; iter < locationX.length ; iter++) {
Component current = (Component)components.elementAt(iter);
locationX[iter] = current.getAbsoluteX() + current.getWidth() / 2 - w / 2;
locationY[iter] = current.getAbsoluteY() + current.getHeight() / 2 - h / 2;
}
if(sequential) {
anim = Motion.createSplineMotion(0, explosions.length - 1, duration / locationX.length);
sequence = new Vector();
} else {
anim = Motion.createSplineMotion(0, explosions.length - 1, duration);
}
anim.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void addComponentsOfClasses(Container c, Vector result) {
for(int iter = 0 ; iter < c.getComponentCount() ; iter++) {
Component current = c.getComponentAt(iter);
if(current instanceof Container) {
addComponentsOfClasses((Container)current, result);
}
for(int ci = 0 ; ci < classes.length ; ci++) {
if(current.getClass() == classes[ci]) {
result.addElement(current);
break;
}
}
}
}
public void cleanup() {
super.cleanup();
explosions = null;
if(sequential) {
components = sequence;
}
if(components != null) {
for(int iter = 0 ; iter < components.size() ; iter++) {
((Component)components.elementAt(iter)).setVisible(true);
}
components.removeAllElements();
}
}
public Transition copy() {
return new ExplosionTransition(duration, classes, sequential);
}
public boolean animate() {
if(sequential) {
if(anim != null && anim.isFinished() && components.size() > 0) {
Component c = (Component)components.elementAt(0);
components.removeElementAt(0);
sequence.addElement(c);
c.setVisible(false);
if(components.size() > 0) {
seqLocation++;
anim.start();
}
return true;
}
return components.size() > 0;
}
if(anim != null && anim.isFinished() && !done) {
// allows us to animate the last frame, we should animate once more when
// finished == true
done = true;
return true;
}
return !done;
}
public void paint(Graphics g) {
getSource().paintComponent(g);
int offset = anim.getValue();
if(sequential) {
g.drawImage(explosions[offset], locationX[seqLocation], locationY[seqLocation]);
return;
}
for(int iter = 0 ; iter < locationX.length ; iter++) {
g.drawImage(explosions[offset], locationX[iter], locationY[iter]);
}
if(offset > 4) {
for(int iter = 0 ; iter < components.size() ; iter++) {
((Component)components.elementAt(iter)).setVisible(false);
}
}
}
}iOS7 allows swiping back one form to the previous form, Codenmae One has an API to enable back swipe transition:
SwipeBackSupport.bindBack(Form currentForm, LazyValue<Form> destination);That one command will enable swiping back from currentForm. LazyValue allows us to pass a value lazily:
public interface LazyValue<T> {
public T get(Object... args);
}This effectively allows us to pass a form and only create it as necessary (e.g. for a GUI builder app we don’t have the actual previous form instance), notice that the arguments aren’t used for this case but will be used in other cases.
About This Guide
Introduction
Basics: Themes, Styles, Components & Layouts
Theme Basics
Advanced Theming
Working With The GUI Builder
The Components Of Codename One
Using ComponentSelector
Animations & Transitions
The EDT - Event Dispatch Thread
Monetization
Graphics, Drawing, Images & Fonts
Events
File-System,-Storage,-Network-&-Parsing
Miscellaneous Features
Performance, Size & Debugging
Advanced Topics/Under The Hood
Signing, Certificates & Provisioning
Appendix: Working With iOS
Appendix: Working with Mac OS X
Appendix: Working With Javascript
Appendix: Working With UWP
Security
cn1libs
Appendix: Casual Game Programming