Home > Back-end >  Animation Drawable Won't Resize Properly
Animation Drawable Won't Resize Properly

Time:09-21

I have a walking dinosaur that I animate using an animation drawable

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item android:drawable="@drawable/dino1" android:duration="@integer/dino_dino" />
    <item android:drawable="@drawable/dino2" android:duration="@integer/dino_dino" />
    <item android:drawable="@drawable/dino3" android:duration="@integer/dino_dino" />
</animation-list>

I want to establish its width using guidelines and calculate its height automatically. I'm accustomed to scaleType doing that for me normal pictures. Like this:

<ImageView
    android:id="@ id/dino"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true"
    android:layout_marginBottom="6dp"
    app:layout_constraintLeft_toLeftOf="@ id/guidelineDinoStart"
    app:layout_constraintRight_toRightOf="@ id/guidelineDinoEnd"
    app:layout_constraintBottom_toBottomOf="parent" />

Indeed, if I add the following line to the above ImageView definition (that is, set its src to be the first frame in the animation):

android:src="@drawable/dino_1"

then I get the properly proportioned image:

enter image description here

If I do the following as code though (and remove the src line from the ImageView definition), the image appears stretched:

_dino = view.findViewById(R.id.dino);

_dino.setBackgroundResource(R.drawable.dino_anim);

AnimationDrawable anim = (AnimationDrawable) _dino.getBackground();

_dino.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        anim.start();
    }
});

enter image description here

And if I comment out the _dino.setBackgroundResource(R.drawable.dino_anim); and set the ImageView definition's src to be the animation:

android:src="@drawable/dino_anim"

then the app crashes when I click (try to start) the animation, saying:

Attempt to invoke virtual method 'void android.graphics.drawable.AnimationDrawable.start()' on a null object reference

How can I set the ImageView to have a properly-proportioned AnimationDrawable (using guidelines for the width but not the height) the way it naturally does if it's just a still picture?

CodePudding user response:

you need to use background OR src for an ImageView. I suggest to use the src, since the resource will be displayed in its original aspect ratio.

Using ImageView's Resource

Just set the resource:

android:src="@drawable/dino_anim"

In the code get the animationDrawable reference from getDrawable() instead of getBackground():

AnimationDrawable anim = (AnimationDrawable) _dino.getDrawable();

Why the crash?

The crash is caused by anim.start();, since the imageView's background is not set when you commented out _dino.setBackgroundResource(R.drawable.dino_anim);.

  • Related