Установите фоновое изображение в относительный макет с помощью Glide в Android
Как это сделать, используя Glide? Я хочу cache
изображение использовать его еще раз. Спасибо заранее.
Ответы
Ответ 1
Вы можете загрузить изображение в RelativeLayout, как это. Я просто показываю вам сложную часть, которая устанавливает изображение на задний план.
Для версии Glide до 4.X
Glide.with(this).load(imageViewPath).asBitmap().into(new SimpleTarget<Bitmap>(relLayoutWidth, relLayoutHeight) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
Drawable drawable = new BitmapDrawable(context.getResources(), resource);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
yourRelativeLayout.setBackground(drawable);
}
}
});
Кэширование см. на этой странице: Кэширование и аннулирование кэша.
Обновление для Glide v4 и выше:
GlideApp.with(this).load(R.drawable.backgroundimage).into(new SimpleTarget<Drawable>() {
@Override
public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
yourRelativeLayout.setBackground(resource);
}
}
});
Ответ 2
Я думаю, что лучший способ его достижения работает с вашей собственной реализацией ViewTarget, потому что у этого класса есть специальные методы, которые Glide автоматически обрабатывает в разных сценариях.
Абстрактная реализация для ViewGroup (LinearLayout, RelativeLayout и т.д.).
public abstract class ViewGroupTarget<Z> extends ViewTarget<ViewGroup, Z> implements GlideAnimation.ViewAdapter {
public ViewGroupTarget(ViewGroup view) {
super(view);
}
/**
* Returns the current {@link android.graphics.drawable.Drawable} being displayed in the view using
* {@link android.widget.ImageView#getDrawable()}.
*/
@Override
public Drawable getCurrentDrawable() {
return view.getBackground();
}
/**
* Sets the given {@link android.graphics.drawable.Drawable} on the view using
* {@link android.widget.ImageView#setImageDrawable(android.graphics.drawable.Drawable)}.
*
* @param drawable {@inheritDoc}
*/
@Override
public void setDrawable(Drawable drawable) {
view.setBackground(drawable);
}
/**
* Sets the given {@link android.graphics.drawable.Drawable} on the view using
* {@link android.widget.ImageView#setImageDrawable(android.graphics.drawable.Drawable)}.
*
* @param placeholder {@inheritDoc}
*/
@Override
public void onLoadStarted(Drawable placeholder) {
view.setBackground(placeholder);
}
/**
* Sets the given {@link android.graphics.drawable.Drawable} on the view using
* {@link android.widget.ImageView#setImageDrawable(android.graphics.drawable.Drawable)}.
*
* @param errorDrawable {@inheritDoc}
*/
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
view.setBackground(errorDrawable);
}
/**
* Sets the given {@link android.graphics.drawable.Drawable} on the view using
* {@link android.widget.ImageView#setImageDrawable(android.graphics.drawable.Drawable)}.
*
* @param placeholder {@inheritDoc}
*/
@Override
public void onLoadCleared(Drawable placeholder) {
view.setBackground(placeholder);
}
@Override
public void onResourceReady(Z resource, GlideAnimation<? super Z> glideAnimation) {
this.setResource(resource);
}
protected abstract void setResource(Z resource);
}
Конкретная реализация, в данном случае для LinearLayout.
public class LinearLayoutTarget extends ViewGroupTarget<Bitmap> {
private Context context;
public LinearLayoutTarget(Context context, LinearLayout linearLayout) {
super(linearLayout);
this.context = context;
}
/**
* Sets the {@link android.graphics.Bitmap} on the view using
* {@link android.widget.ImageView#setImageBitmap(android.graphics.Bitmap)}.
*
* @param resource The bitmap to display.
*/
@Override
protected void setResource(Bitmap resource) {
view.setBackground(new BitmapDrawable(context.getResources(), resource));
}
}
Для работы с.
Glide.with(this.getApplicationContext())
.load(R.drawable.your_image)
.asBitmap()
.into(new LinearLayoutTarget(this.getApplicationContext(), (LinearLayout) yourLinearLayoutInstanceHere));
Или даже более простая работа без Bitmap.
Конкретная реализация.
public class LinearLayoutTarget extends ViewGroupTarget<Drawable> {
public LinearLayoutTarget(LinearLayout linearLayout) {
super(linearLayout);
}
/**
* Sets the {@link android.graphics.Bitmap} on the view using
* {@link android.widget.ImageView#setImageBitmap(android.graphics.Bitmap)}.
*
* @param resource The bitmap to display.
*/
@Override
protected void setResource(Drawable resource) {
view.setBackground(resource);
}
}
Для работы с.
Glide.with(this.getApplicationContext())
.load(R.drawable.your_image)
.into(new LinearLayoutTarget((LinearLayout) yourLinearLayoutInstanceHere));
Ответ 3
В настоящее время в версии Glide версии 4.9.0 вы можете установить фон для Relative Layout следующим образом: -
Glide.with(MainActivity.this)
.load(IMAGE_URL)
.into(new CustomTarget<Drawable>() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
mLinearLayout.setBackground(resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
Ответ 4
(Класс SimpleTarget устарел, поэтому для загрузки изображения используется класс CustomTarget)
Вы можете загрузить изображение в RelativeLayout, как это. Я просто показываю вам сложную часть, которая устанавливает изображение на задний план.
Для версии Glide до 4.X (без устаревания)
Glide.with(this).load(ServiceGenerator.BASE_URL + url).into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
yourRelativeLayout.setBackground(resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
Ответ 5
Спасибо всем. Все ваши ответы помогли мне. Я также нахожу полезные решения с официальной документацией Glide. Я переключился на Модуль Приложения Glide, чтобы иметь общее использование этого.
https://medium.com/@nuhkocaa/manage-all-your-glides-in-a-single-class-with-glidemodule-on-android-4856ee4983a1