【发布时间】:2021-03-18 02:14:00
【问题描述】:
我尝试使用 Glide 加载外部图像并将其显示在工具栏中。我有以下代码(在片段内):
ImageView image = null;
Glide.with(this)
.load("https://images.unsplash.com/photo-1612138210955-363d1ba3477d?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max")
.into(image);
binding.toolbar.setBackgroundResource(image);
方法 'binding.toolbar.setBackgroundResource()' 需要一个 int 但从 Glide 加载的图像是一个 imageView。现在我的问题是,如何将 Glide 加载的图像转换为可以使用方法 'binding.toolbar.setBackgroundResource(image)' 的 int 类型?我会很感激每一条评论。
更新:我尝试了一个答案中的建议代码,如下所示:
ImageView image = new ImageView(getContext());
image.setDrawingCacheEnabled(true);
Glide.with(this).load("https://images.unsplash.com/photo-1614907301762-405163ba662f?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80")
.into(image);
Bitmap bmap = image.getDrawingCache();
binding.toolbar.setBackground(new BitmapDrawable(getResources(), bmap));
基本上我现在没有收到错误。但是,代码应该设置工具栏的背景。基本上,使用建议的代码时,工具栏看起来很糟糕,因为我看不到图片,而只是一个白色区域。我认为问题出在 URL 上。我使用不存在的 URL 进行了尝试,得到了相同的结果。只是一个白色的区域。所以这意味着 Glide 无法加载图像,尽管 URL 本身是正确的。你能想出这个问题出现的具体原因吗? ——
由于我还没有收到包含我的问题的解决方案的答案,所以我想再次询问您是否知道如何解决问题?如何通过 Glide 从 URL 加载图像并将其作为工具栏的背景插入?
【问题讨论】:
-
为什么你不能使用 setBackgroundDrawable() 或只使用 setBackground(),它不是用于工具栏吗?从位图绘制会更容易。
-
感谢 AndroidKiller 的评论。使用 setBackground() 时,我仍然收到一条错误消息,告诉我所需类型:Drawable 提供:ImageView
-
@AndroidKiller:我最后一个 cmets 上有没有 cmets?我非常感谢您的每进一步评论
-
@VanessaF 我已经发布了解决方案作为答案,你能试试吗???
标签: android android-imageview android-glide