Search code examples
androidimageandroid-imageviewuniversal-image-loader

How to avoid image flickering in a listview


I have a listivew that display a bunch of images. am using Universal Image Loader to load this images from files to imageviews.

This images have different dimensions and i want all of them to have same width but different height in respect to each image aspect ratio.

To achieve this, i have tried setting the following to my imageview

<ImageView
   android:layout_width = "400dp"
   android:layout_height="wrap_content"
   android:scaleType="centerCrop"
   android:adjustViewBounds="true"/>

The issue with this method is that there is a lot of flickering when one scrolls the listview since imageview height is not known in advance and images have to be scaled first using my width to calculate each image height in respect to it's aspect ratio.

How can i calculate each image height in advance instead of letting imageview handle it?

if i have an image which is 400 X 700, and i want the imageview to be 300px wide, how can i calculate imageview's height using my image dimension and maintain image aspect ratio? this can help avoid flickering wnen one scroll the listview.


Solution

  • After hours of research, i was able to know the method that i can use to calculate new imageview height while maintaining image aspect ratio.

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
    
    //Returns null, sizes are in the options variable
    BitmapFactory.decodeFile("/sdcard/image.png", options);
    int width = options.outWidth;
    int height = options.outHeight;
    
    //calculating image aspect ratio
    float ratio =(float) height/(float) width;
    
    //calculating my image height since i want it to be 360px wide
    int newHeight = Math.round(ratio*360);
    
    //setting the new dimentions
     imageview.getLayoutParams().width = 360;
     imageview.getLayoutParams().height = newHeight;
    
     //i'm using universal image loader to display image
     imaheview.post(new Runnable(){
      ImageLoader.getInstance().displayImage(imageuri,imageview,displayoptions);
     });