Created
October 3, 2014 22:29
-
-
Save mikehearn/f639176566d735b676e7 to your computer and use it in GitHub Desktop.
animatedBind
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class AnimatedBindInfo { | |
@Nullable public Timeline timeline; | |
public NumberBinding bindFrom; | |
public Runnable onAnimFinish; | |
} | |
public static AnimatedBindInfo animatedBind(Node node, WritableDoubleValue bindTo, NumberBinding bindFrom) { | |
bindTo.set(bindFrom.doubleValue()); // Initialise. | |
bindFrom.addListener((o, prev, cur) -> { | |
AnimatedBindInfo info = (AnimatedBindInfo) node.getUserData(); | |
if (info.timeline != null) | |
info.timeline.stop(); | |
info.timeline = new Timeline(new KeyFrame(UI_ANIMATION_TIME, new KeyValue(bindTo, cur))); | |
info.timeline.setOnFinished(ev -> { | |
((AnimatedBindInfo) node.getUserData()).timeline = null; | |
if (info.onAnimFinish != null) | |
info.onAnimFinish.run(); | |
}); | |
info.timeline.play(); | |
}); | |
// We must pin bindFrom into the object graph, otherwise something like: | |
// animatedBind(node, node.opacityProperty(), when(a).then(1).otherwise(2)) | |
// will mysteriously stop working when the result of when() gets garbage collected and the listener with it. | |
AnimatedBindInfo info = new AnimatedBindInfo(); | |
info.bindFrom = bindFrom; | |
node.setUserData(info); | |
return info; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Really nice utility!
Regarding the comment in the code, wouldn't it be sufficient to require the user to store a reference to
AnimatedBindInfo
to keep the animation working? This would eliminate the need to pass in aNode
altogether. The listener would have to be a closure over theAnimatedBindInfo
instance instead of over the node.If you find pinning it to a Node a convenient way to keep the reference, there could be a convenient method
AnimatedBindInfo.pin(Node node)
to do this.