问题描述
APP首页用的是Fragment,然后用开源库Banner来实现轮播图,图片加载用的是Glide,然而一张都出不来。
原因
Glide4.0的问题
使用Glide的依赖为
implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
Glide4.0以上需要自定义一个类
@GlideModule
public class MyAppGlideModule extends AppGlideModule {
}
build之后会生成一个GlideApp.这样就可以使用了。
如果你添加的依赖为
implementation 'com.github.bumptech.glide:glide:4.8.0'
implementation 'com.github.bumptech.glide:compiler:4.8.0'
build的时候会报错,此时你需要在gradle的defaultconfig添加下面这句
javaCompileOptions {
// 显式声明支持注解
annotationProcessorOptions {
includeCompileClasspath true
}
}
这样就可以build成功。
上下文的问题
在使用banner的时候需要设置图片加载器:
banner.setImageLoader(new GlideImageLoader());
public class GlideImageLoader extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
Glide.with(context)
.load((String) path)
.into(imageView);
}
}
其中ImageLoader是banner中封装好的,我们只需要继承一下即可。
在这里需要注意的是glide中的上下文如果使用的是displayImage中的context,也可能导致加载图片不出来。从网上资料查阅得,Glide获取容器生命周期的机制与其他开源框架产生了冲突,故而导致图片加载失效
解决的方法有两种:
1、上下文需要填
Glide.with(context.getApplicationContext).load((String) path).into(imageView);
2、换用其他的第三方图片加载
在这里使用的是ImageLoader。
依赖为:
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
在Application中初始化
// 创建DisplayImageOptions对象
DisplayImageOptions defaulOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true).build();
// 创建ImageLoaderConfiguration对象
ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaulOptions)
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.diskCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO).build();
// ImageLoader对象的配置
ImageLoader.getInstance().init(configuration);
然后再banner中设置
banner.setImageLoader(new ImageLoader() {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
com.nostra13.universalimageloader.core.ImageLoader imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
imageLoader.displayImage((String) path,imageView);
}
});
9.0系统问题
还有一种是9.0的系统导致图片显示不出来,因此需要在
<application
android:allowBackup="true"
android:name=".MyApplication"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/AppBaseTheme"/>
设置android:usesCleartextTraffic="true"即可