Creating animation on ImageView while changing image resource

后端 未结 4 1362
情深已故
情深已故 2020-12-01 02:23

I have only one ImageView in my layout and I am changing its resource when a gasture event detected. I just want to show an animation while changing resource of

4条回答
  •  青春惊慌失措
    2020-12-01 02:34

    I found another way to animate it using transition drawable(I took idea from here)

        public static void setImageDrawableWithAnimation(ImageView imageView,
                                                         Drawable drawable,
                                                         int duration) {
        Drawable currentDrawable = imageView.getDrawable();
        if (currentDrawable == null) {
            imageView.setImageDrawable(drawable);
            return;
        }
    
        TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[] {
                currentDrawable,
                drawable
        });
        imageView.setImageDrawable(transitionDrawable);
        transitionDrawable.startTransition(duration);
    }
    

    Analogous kotlin extension function:

    fun ImageView.setImageDrawableWithAnimation(drawable: Drawable, duration: Int = 300) {
        val currentDrawable = getDrawable()
        if (currentDrawable == null) {
            setImageDrawable(drawable)
            return
        }
    
        val transitionDrawable = TransitionDrawable(arrayOf(
                currentDrawable,
                drawable
        ))
        setImageDrawable(transitionDrawable)
        transitionDrawable.startTransition(duration)
    }
    

    If your drawables contains transparent parts, this flag could be useful to prevent old drawable visibility:

    transitionDrawable.setCrossFadeEnabled(true);
    

提交回复
热议问题