1
votes

I have an ImageView that I previously used to display images with

imageview.setImageResource(R.drawable.my_image);

I defined the scaleType to centerCrop in the XML-layout to keep the image's aspect ratio

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image_view"
        android:src="@drawable/my_image"
        android:scaleType="centerCrop" />

Now I need to use a drawable animation in the ImageView and that is set to the imageView's background.

Layout file:

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image_view"
        android:src="@android:color/transparent"
        android:scaleType="centerCrop" />

Java:

AnimationDrawable animDraw;

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  ImageView imageview = (ImageView) findViewById(R.id.image_view);
  imageview.setBackgroundResource(R.drawable.my_animation);
  animDraw = (AnimationDrawable) imageview.getBackground();
}

public boolean onTouchEvent(MotionEvent event) {
  if (event.getAction() == MotionEvent.ACTION_DOWN) {
    animDraw .start();
    return true;
  }
  return super.onTouchEvent(event);
}

my_animation drawable

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true">
    <item android:drawable="@drawable/my_image1" android:duration="150" />
    <item android:drawable="@drawable/my_image2" android:duration="150" />
    <item android:drawable="@drawable/my_image3" android:duration="150" />
</animation-list>

The animation works fine but the drawable is now set to the background and I cannot change its scaleType to keep the aspect ratio.

Is there some way to get the animation to keep the aspect ratio?

1

1 Answers

0
votes
imageview.setImageResource((R.drawable.my_animation);

You have to set imageRecource instead of imageBackground.
Scale type doesn't work with setBackground.

For more: How do I set an ImageViews source programmatically in Android?