Skip to content

Instantly share code, notes, and snippets.

@tushar-nallan
Last active May 14, 2019 02:00
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tushar-nallan/bc76d15ca6eabf2e6c2b0a6994efde43 to your computer and use it in GitHub Desktop.
Save tushar-nallan/bc76d15ca6eabf2e6c2b0a6994efde43 to your computer and use it in GitHub Desktop.
Implement a checkbox using lottie animations
import android.animation.Animator;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import com.airbnb.lottie.LottieAnimationView;
public class LottieCheckBox extends LottieAnimationView implements Checkable, Animator.AnimatorListener {
private boolean checked;
private boolean isFirstLoad = true;
private OnCheckedChangeListener listener;
private static final String ANIMATION_ASSET = "animation-asset.json";
public LottieCheckBox(Context context) {
super(context);
initLottieCheckBox();
}
public LottieCheckBox(Context context, AttributeSet attrs) {
super(context, attrs);
initLottieCheckBox();
}
public LottieCheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initLottieCheckBox();
}
private void initLottieCheckBox() {
setOnClickListener(v -> toggle());
// If any images are required for the animation json
setImageAssetsFolder("images/");
loop(false);
setAnimation(ANIMATION_ASSET, CacheStrategy.Weak);
addAnimatorListener(this);
}
@Override public void setChecked(boolean checked) {
this.checked = checked;
if (isFirstLoad) {
setInitState();
isFirstLoad = false;
} else {
if (checked) {
reverseAnimation();
} else {
playAnimation();
}
}
}
private void setInitState() {
setProgress(checked ? 0 : 1f);
}
@Override public boolean isChecked() {
return checked;
}
@Override public void toggle() {
setChecked(!checked);
}
public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
this.listener = listener;
}
@Override public void onAnimationStart(Animator animation) {
}
@Override public void onAnimationEnd(Animator animation) {
if (listener != null) {
listener.onCheckedChanged(this, checked);
}
}
@Override public void onAnimationCancel(Animator animation) {
}
@Override public void onAnimationRepeat(Animator animation) {
}
public interface OnCheckedChangeListener {
void onCheckedChanged(LottieCheckBox lottieCheckBox, boolean checked);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment