Cannot start this animator on a detached view

1.9k Views Asked by At

Can anyone tell me whats wrong with this?

View view = findViewById(R.id.thumbnail_image_header); // thumbnail_image_header is an imageView

    int cx = (view.getLeft() + view.getRight()) / 2;
    int cy = (view.getTop() + view.getBottom()) / 2;

    // get the final radius for the clipping circle
    int dx = Math.max(cx, view.getWidth() - cx);
    int dy = Math.max(cy, view.getHeight() - cy);
    float finalRadius = (float) Math.hypot(dx, dy);

    // Android native animator
    Animator animator =
            ViewAnimationUtils.createCircularReveal(view, cx, cy, 0, finalRadius);
    animator.setInterpolator(new AccelerateDecelerateInterpolator());
    animator.setDuration(1500);
    animator.start();
2

There are 2 best solutions below

0
yatin deokar On

Add animation under addOnLayoutChangeListener of MainLayout .

mainView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
            view.removeOnLayoutChangeListener(this);

            //Add circular revel animation on activity start
            mainView.post(new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    //Your Animation Code
                }
            });

        }
    });
0
goemic On

You can check if the view is currently attached or not. If not add an OnAttachStateChangeListener and start the animation as soon as the view is attached.

if (view.isAttachedToWindow()) {

    // startAnimation..

} else {
    view.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
        @Override
        public void onViewAttachedToWindow(View v) {                
            v.removeOnAttachStateChangeListener(this);

            // startAnimation..

        }
        
        @Override
        public void onViewDetachedFromWindow(View v) {
        }
    });
}