开源框架 ImageLoader +ListView+GridView+RecyclerView 浅解
下载地址
链接:https://pan.baidu.com/s/1ebz99pcuvHg2bODgeOtSbg 提取码:ia39
一、导入jar包或者添加依赖
导入jar包:将下载的jar包放入到libs目录下,右键选择 “Add as Library”
添加依赖:compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
二、添加权限
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
三、主要方法
//不要将这段代码拷贝进你的工程。这仅仅是所有配置选项使用的范例。 // 查看sample工程来学习如何正确的使用ImageLoader //这里的路径可以自定义 File cacheDir = StorageUtils.getOwnCacheDirectory(this,"image/photo") File cacheDir = StorageUtils.getCacheDirectory(this); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this) // 默认等于你的屏幕尺寸,设备屏幕宽高 .memoryCacheExtraOptions(480, 800) // 在将下载的图片保存到你的sd卡之前会重新计算,压缩。 // 这个属性不要滥用,只有你在对应的需求时再用,因为他会使你的ImageLoader变的很慢。 .diskCacheExtraOptions(480, 800, null) //用于执行从源获取图片任务的 Executor,为configuration中的 taskExecutor, // 如果为null,则会调用DefaultConfigurationFactory.createExecutor(…)根据配置返回一个默认的线程池。 .taskExecutor(null) //用于执行从缓存获取图片任务的 Executor,为configuration中的 taskExecutorForCachedImages, // 如果为null,则会调用DefaultConfigurationFactory.createExecutor(…)根据配置返回一个默认的线程池。 .taskExecutorForCachedImages(null) // 表示核心池大小(最大并发数) 默认为3 .threadPoolSize(3) // 线程优先级,默认Thread.NORM_PRIORITY - 2 .threadPriority(Thread.NORM_PRIORITY - 2) // 任务进程的顺序,默认为:FIFO 先进先出 .tasksProcessingOrder(QueueProcessingType.FIFO) //设置内存缓存不允许缓存一张图片的多个尺寸,默认允许。 .denyCacheImageMultipleSizesInMemory() //图片内存缓存 .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //memoryCacheSize 为 0,则设置该内存缓存的最大字节数为 App 最大可用内存的 1/8。 .memoryCacheSize(2 * 1024 * 1024) // 创建最大的内存缓存百分比,默认为 13% .memoryCacheSizePercentage(13) // 硬盘缓存路径,默认为StorageUtils.getCacheDirectory(context) .diskCache(new UnlimitedDiskCache(cacheDir)) //硬盘缓存大小 .diskCacheSize(50 * 1024 * 1024) //缓存文件数量 .diskCacheFileCount(100) // 硬盘缓存文件名生成器,默认为哈希文件名生成器 .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // 创建图片下载器,默认是BaseImageDownloader .imageDownloader(new BaseImageDownloader(this)) // 图片解码器,负责将图片输入流InputStream转换为Bitmap对象 .imageDecoder(new BaseImageDecoder(true)) // 图片显示的配置项。比如加载前、加载中、加载失败应该显示的占位图片,图片是否需要在磁盘缓存,是否需要在内存缓存等。 .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) //是否显示调试log信息 .writeDebugLogs() .build(); ImageLoader.getInstance().init(config);
// 加载图片 DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.ic_stub) // resource or drawable .showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable .showImageOnFail(R.drawable.ic_error) // resource or drawable .resetViewBeforeLoading(false) // default .delayBeforeLoading(1000) .cacheInMemory(false) // default .cacheOnDisk(false) // default .preProcessor(...) .postProcessor(...) .extraForDownloader(...) .considerExifParams(false) // default .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default .bitmapConfig(Bitmap.Config.ARGB_8888) // default .decodingOptions(...) .displayer(new SimpleBitmapDisplayer()) // default .handler(new Handler()) // default .build(); ImageLoader.getInstance().displayImage(imageUrl, imageView); ImageLoader.getInstance().displayImage(imageUrl, imageView,options); ImageLoader.getInstance().displayImage(imageUrl, imageView, options, listener); new ImageLoadingListener() { @Override public void onLoadingStarted(String s, View view) { } @Override public void onLoadingFailed(String s, View view, FailReason failReason) { } @Override public void onLoadingComplete(String s, View view, Bitmap bitmap) { } @Override public void onLoadingCancelled(String s, View view) { } })
四 、具体使用
github https://github.com/MichealPan9999/ImageLoader
4.1 配置ImageLoaderConfiguration
public class BaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
initImageLoaderConfig(getApplicationContext());
}
private void initImageLoaderConfig(Context context)
{
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.NORM_PRIORITY - 2 )
.threadPoolSize(3)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.FIFO)
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config);
}
}
AndroidManifast中修改
<application android:name=".BaseApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">
4.2 配置DisplayImageOptions
private void initImageOptions() { options = new DisplayImageOptions.Builder() .showStubImage(R.drawable.ic_robot) .showImageForEmptyUri(R.drawable.ic_robot) .showImageOnFail(R.drawable.ic_robot) .cacheInMemory(true) .cacheOnDisc(true) .displayer(new RoundedBitmapDisplayer(20)) .build(); }
4.3 加载ImageLoader.getInstance.displayImage(...)
imageLoader = ImageLoader.getInstance();
... imageLoader.displayImage(imageUrls[i],viewHolder.image,options,animateFirstListener);
//第一个参数为地址,第二个参数为存放图片的控件ImageView第三个参数为DisplayImageOpetions具体实例化,第四个参数为加载过程监听事件。
五、RecyclerView
借此机会介绍一下RecyclerView
5.1 手动导包
RecyclerView在Android5.0之后才有,使用时必须导入support-v7包。
如果在配置布局时发现找不到RecyclerView控件那么我们就得手动导包了
1、找到sdk目录下的aar文件 如:recyclerview-v7-25.0.0.aar
D:\Program Files\androidstudio3\sdk2\extras\android\m2repository\com\android\support\recyclerview-v7\25.0.0\recyclerview-v7-25.0.0.aar
<android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
2.将aar拷贝到项目libs目录下
3.配置build.gradle
方法一、
在当前module下的build.gradle加上如下红色标识的内容,点击右上角sync now,一段时间后发现此时可以加载到RecyclerView控件说明OK
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.panzq.imageloader2"
minSdkVersion 22
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding{
enabled = true;
}
}
repositories {
flatDir {
dirs 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.+'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile(name: 'recyclerview-v7-25.0.0', ext: 'aar')
implementation files('libs/universal-image-loader-1.9.5.jar')
}
方法二
implementation 'com.android.support:recyclerview-v7:28.0.2'
5.2 获取RecyclerView并配置LayoutManager
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, RecyclerView.VERTICAL));
此处setLayoutManager是设置RecyclerView以哪种形式设置,包括以下三种形式
1.LinearLayoutManager 线性管理器,支持横向、纵向。
//第一个参数获取Context,第二个参数表示方向RecyclerView.HORIZONTAL跟RecyclerView.VERTICAL,第三个表示是否反转
mRecyclerView.setLayoutManager(new LinearLayoutManager(this,RecyclerView.VERTICAL,true));
2.GridLayoutManager 网格布局管理器
//第一个参数表示Context,第二个表示显示多少列
mRecyclerView.setLayoutManager(new GridLayoutManager(this,4));
3.StaggeredgridLayoutManager 瀑布式布局管理器
//第一个参数表示显示3行/列 表示垂直翻页还是竖直翻页
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, RecyclerView.HORIZONTAL));
5.3 配置Adapter
继承RecyclerView.Adapter<VH>
Adapter主要区别在于
//通过构造方法传入加载布局文件得到的view对象 @Override public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { return new RecyclerViewHolder(LayoutInflater.from(mContext).inflate(R.layout.recycler_item, viewGroup, false)); } @Override public void onBindViewHolder(RecyclerViewHolder recyclerViewHolder, int i) { //通过itemview得到每个图片的pararms对象 RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) recyclerViewHolder.itemView.getLayoutParams(); //将高度修改为传入的随机高度 params.height = heights.get(i); //设置修改参数 recyclerViewHolder.itemView.setLayoutParams(params); //通过loader对象的displayImage方法将网址中下载的图片按照设置的图片配置显示再imageview中 loader.displayImage(ImageURL[i], recyclerViewHolder.imageView, dios); }
效果
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次 .NET 某发证机系统 崩溃分析
· 微服务架构学习与思考:SOA架构与微服务架构对比分析
· tomcat为什么假死了
· 聊一聊 Linux 上对函数进行 hook 的两种方式
· C# 锁机制全景与高效实践:从 Monitor 到 .NET 9 全新 Lock
· 一周 Star 破万的开源项目「GitHub 热点速览」
· 千万级大表,如何做性能调优?
· 编码之道,道心破碎。
· 不写代码,让 AI 生成手机 APP!保姆级教程
· 记一次 .NET 某发证机系统 崩溃分析