Tuesday, 17 November 2015

Loading images in a GridView or Listview from drawables at Runtime using Imageloader



You can use this code where you want to get the dynamic resource id (i.e in int). I Mostly used in Adapters (for gridview, listview).

ImageArray for dummy purpose

String[] imagesArray={"image1","image2","image3","image4","image5","image6"};
   

First Declare your imageloader

ImageLoader mImageloader;


Define your DisplayOptions as per requirement

mImageOptions = new DisplayImageOptions.Builder()
        .showImageOnLoading(R.drawable.ic_launcher)
        .showImageForEmptyUri(R.drawable.ic_launcher)
        .showImageOnFail(R.drawable.ic_launcher)
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .considerExifParams(true)
        .bitmapConfig(Bitmap.Config.RGB_565)
        .build();


Define config as per requirement   

   
 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext)
        .threadPriority(Thread.NORM_PRIORITY - 2)
        .denyCacheImageMultipleSizesInMemory()
        .diskCacheFileNameGenerator(new Md5FileNameGenerator())
        .diskCacheSize(50 * 1024 * 1024) // 50 Mb
        .tasksProcessingOrder(QueueProcessingType.LIFO)
        .writeDebugLogs() // Remove for release app
        .build();
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
        mImageloader=ImageLoader.getInstance();

        
Then Load your image into your imageview
mImageloader
        .displayImage(("drawable://" + getResourceId(imagesArray[index],"drawable","com.example.dummy", mContext)), YourImageView, mImageOptions, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            }
        }, new ImageLoadingProgressListener() {
            @Override
            public void onProgressUpdate(String imageUri, View view, int current, int total) {
            }
        });
        
        

Use this method to get the resource id
public  int getResourceId(String fileName, String resourceName, String packageName,Context mContext) 
    {
        try {
            return mContext.getResources().getIdentifier(fileName, resourceName, packageName);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } 
    }       

                           

No comments:

Post a Comment