Image-loader的使用方式

来源:互联网 发布:盗版游戏 知乎 编辑:程序博客网 时间:2024/06/05 09:23

今天来介绍一下image-loader的具体配置和使用方式

image-loader就是著名的图片加载框架Universal-Image-Loader,其优缺点在此不再一一陈述,也不再叙述其原理几何。因为大部分人还是比较注重,该怎么去用它。

使用前

1.百度搜索 universal-image-loader可找到相应jar包下载
2.新建android工程,将下载的jar文件放进libs里,并依赖
3.新建工具类,可命名为 ImageLoaderUtils

public class ImageLoaderUtils {    private static DisplayImageOptions options =        new DisplayImageOptions.Builder()            //下载过程中显示的图片            .showImageOnLoading(R.drawable.car_head)            //下载失败时显示的图片            .showImageOnFail(R.drawable.car_head)            //uri为空的时候显示的图片            .showImageForEmptyUri(R.drawable.car_head)            //是否进行内存缓存            .cacheInMemory(true)            //            .cacheOnDisk(true)            //            //bitmapConfig(Bitmap.Config.RGB_565)            .resetViewBeforeLoading(true)            .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)            .displayer(new FadeInBitmapDisplayer(200))//            RoundedBitmapDisplayer            .build();    //file://    public static void display(String url,ImageView imageView){        ImageLoader.getInstance().displayImage(url, imageView, options);    }}

在工具类中可针对实际情况进行配置,比如在本例中,分别添加了在加载过程中、加载失败以及图片链接为空时imageview应该显示的图片,大家在使用时可设置不同的图片来体现不一样的效果。

4.在application中配置Imagerloader,并且初始化。不至于每次调用的时候都重写一次。
application的作用不用言说,一般都懂。我们新建一个MyApplication继承自Application,在onCreate()里配置

 //配置ImageLoader        ImageLoaderConfiguration config             =new ImageLoaderConfiguration.Builder(this)                //不要缓存不同尺寸                .denyCacheImageMultipleSizesInMemory()                //下载图片线程的优先级                .threadPriority(Thread.NORM_PRIORITY-2)                //设置下载线程的执行器(线程池)                .taskExecutor(ExectorManager.getInstance().getExectors())                //设置内存缓存的大小                .memoryCacheSize((int)Runtime.getRuntime().maxMemory()/8)                //设置磁盘缓存大小                .diskCacheSize(50*1024*1024)                //设置磁盘缓存文件的命名生成器                .diskCacheFileNameGenerator(new Md5FileNameGenerator())                //设置磁盘缓存的路径                .discCache(new UnlimitedDiskCache(FileUitlity.getInstance(this).makeDir("imageCache")))                //                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())                //设置具体的图片加载器:                .imageDownloader(new BaseImageDownloader(this, 60*1000, 60*1000))                //生成配置信息                .build();        ImageLoader.getInstance().init(config);

在上述代码中牵扯到了线程池的概念,其定义自行查阅,在此列出本例所用到的线程池

public class ExectorManager {    /**     * 单例模式     */    //提供静态常量,存储数据    private static ExectorManager instance;    public static ExectorManager getInstance(){        if(instance==null){//判断是否第一次调用            synchronized (ExectorManager.class) {                if(instance==null){                    instance=new ExectorManager();                }            }            instance=new ExectorManager();        }        return instance;    }    //定义线程执行器    private ExecutorService executorService;    //私有化构造函数    private ExectorManager(){        inti();    }    private void inti(){        //初始化线程池        int max=8;        int num=Runtime.getRuntime().availableProcessors()*2+1;        num=num>max?max:num;        executorService= Executors.newFixedThreadPool(num);    }    /**     * 执行任务     * @param runnable     */    public void execute(Runnable runnable){        this.executorService.execute(runnable);    }    public ExecutorService getExectors(){        return this.executorService;    }}

还有一个关于磁盘缓存路径的工具类

public class FileUitlity {    private static String ROOT_CACHE;    public static String ROOT_DIR="file_name";    private static FileUitlity instance = null;    private FileUitlity() {    }    public static FileUitlity getInstance(Context context) {        if (instance == null) {            if (Environment.getExternalStorageState().equals(                    Environment.MEDIA_MOUNTED)) {                ROOT_CACHE = (Environment.getExternalStorageDirectory() + "/"                        + ROOT_DIR + "/");            } else {                ROOT_CACHE = (context.getFilesDir().getAbsolutePath() + "/"+ROOT_DIR+"/");            }            File dir = new File(ROOT_CACHE);            if (!dir.exists()) {                dir.mkdirs();            }            instance = new FileUitlity();        }        return instance;    }    public File makeDir(String dir) {        File fileDir = new File(ROOT_CACHE + dir);        if (fileDir.exists()) {            return fileDir;        } else {            fileDir.mkdirs();            return fileDir;        }    }}

5.配置Android Manifest文件

<application        android:name=".MyApplication"        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity            android:name=".MainActivity"            android:launchMode="singleTask">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity></application>

使用

配置完毕,使用就很简单了,不管是在activity,fragment,还是adapter里,都是一句代码搞定

ImageLoaderUtils.display(url,imageview);

url:是你图片链接,或者你本地图片路径,imageview是你ImageView控件。

完事了,是不是很简单呢。轻松一配置,开发工作就简单省事了许多。 本人开发小白,若有大神看到有瑕疵,还望指正!

原创粉丝点击