2017-12-27 96 views
3

設置我有我的應用程序內的幾個RecyclerView的,和所有的人都該有一個ImageView項目,這是與Glide進一步填充,這樣不加載圖片:泰爾滑翔如果偏好

Glide.with(context) 
.load(imageUrl) 
.asBitmap() 
.error(R.drawable.placeholder_avatar) 
.centerCrop() 
.into(mAvatarImageView); 

在我的首選項屏幕中,用戶可以禁用加載所有遠程圖像以節省帶寬。 什麼是最好的方式告訴Glide不加載圖像,而不在所有RecyclerView適配器內使用經典的if-else條件,這違反了DRY原則?

我正在尋找這樣的方法:

.shouldLoad(UserSettings.getInstance().isImageLoadingEnabled()); 
+2

從我經歷了滑翔,他們沒有選擇不加載,因爲它沒有意義。您可以使用您想要使用的首選項來創建經典的if語句:if(UserSettings.getInstance()。isImageLoadingEnabled()){} –

+0

對於此問題,唯一可靠的來源是https://bumptech.github.io/glide/。 –

回答

2

如果你決定使用Kotlin您可以創建所需的擴展功能:

fun <T> RequestBuilder<T>.shouldLoad(neededToLoad : Boolean) : RequestBuilder<T> { 
    if(!neededToLoad) { 
     return this.load("") // If not needed to load - remove image source 
    } 
    return this // Continue without changes 
} 

然後你可以使用它如你有問題描述:

Glide.with(context) 
     .load(imageUrl) 
     .shouldLoad(false) 
     .into(imageView) 


這是公平地說,你可以用shouldLoad()功能只創建一個Kotlin文件和Java使用它,但代碼變得醜陋:

shouldLoad(Glide.with(this) 
       .load(imageUrl), false) 
      .into(imageView); 

OR

RequestBuilder<Drawable> requestBuilder = Glide.with(this) 
     .load(imageUrl); 
requestBuilder = shouldLoad(requestBuilder, true); 
requestBuilder.into(imageView); 
3

假設你正在使用滑翔V4,有專門爲此設計了一個請求選項:RequestOptions.onlyRetrieveFromCache(boolean flag)。啓用時,只加載內存或磁盤緩存中已有的資源,有效防止來自網絡的負載並節省帶寬。

如果您使用Glide v4生成的API,則此選項可直接在GlideApp.with(context).asBitmap()返回的GlideRequest上使用。 否則,您必須創建一個RequestOptions使用此標誌啓用,apply它:

RequestOptions options = new RequestOptions().onlyRetrieveFromCache(true); 
Glide.with(context).asBitmap() 
    .apply(options) 
    .error(R.drawable.placeholder_avatar) 
    .centerCrop() 
    .into(mAvatarImageView); 
+0

如果用戶想要啓用獲取遠程圖像,該怎麼辦?他仍然必須作出if條件 –

+1

您可以在我的示例中將'!UserSettings.getInstance()。isImageLoadingEnabled()'傳遞給'onlyRetrieveFromCache'而不是'true'。這樣,用戶可以啓用/禁用首選項屏幕中的遠程圖像獲取。 –

+0

我偶然發現了這個,但用戶界面不會很好。想象一下'RecyclerView',它具有隨機加載圖像的項目。除此之外,用戶會抱怨圖像仍在加載,儘管從緩存中加載。 – azurh