是否可以从资源文件夹中加载可绘制对象?
您可以从assets(不是drawable文件夹)文件夹中的子目录加载drawable吗?
Can you load a drawable from a sub directory in the assets
(not the drawable folder) folder?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
希望这有帮助:
Hope this help:
我建议使用它,
由于资源的原因,它会返回正确缩放的可绘制对象......
I recommend to use this
which returns properly scaled drawable thanks to resources ...
这是一个带有静态方法的类,用于从资源中获取可绘制对象。它还关闭输入流。
Here's a class with static method to get the drawable from the assets. It also closes the inputstream.
是的,您可以使用 createFromStream() 方法。
Yes you can create a
Drawable
object from anInputStream
using the createFromStream() method.这是为您执行此操作的函数。
检查返回的 Drawable 变量是否为 null,因为如果路径无效或存在 IOException,则可能会返回 null。
Here is function that does this for you.
Check the returned Drawable variable for null as null may return if the path is invalid or there is an IOException.
我正在 RecyclerView 适配器中工作,发现 David's 的答案对我不起作用,(由于某种原因,无论我导入什么,
asset.open
仍然无法解决),所以我发现这对我有用(Kotlin 代码)
这里是我的目录,你可以看到资产从资产文件夹开始,这里是 链接,了解如何创建该资源文件夹
I was working in a RecyclerView adapter and found that David's answer was not working for me, (for some reason
asset.open
remained Unresolved no matter what I imported )so I found this to work for me (Kotlin code)
here is my directory, as you can see the assets start from the assets folder and here is a link on how to create that assets folder
这有助于获得正确的密度
This helped getting the right density
用于从资产中获取可绘制对象的 Kotlin 函数
感谢 @Bart Burg,
我已将 Java 函数改编为 Kotlin,用于从资产文件夹中检索
Drawable
。 Kotlin 版本利用该语言的标准库函数来实现高效、安全的资源管理。这是 Kotlin 的实现:Kotlin Function to Get Drawable from Assets
Thanks to @Bart Burg
I've adapted a Java function to Kotlin for retrieving a
Drawable
from the assets folder. The Kotlin version utilizes the language's standard library functions for efficient and safe resource management. Here's the Kotlin implementation:在此版本中,您不能,如果您在可绘制文件夹中创建子文件夹,则无法在 xml 文件中使用它,当您使用 android:src 时,它不会被识别。
看一下这个帖子:Android 可绘制目录可以包含子目录吗?
At this version you can't, if you make a sub folder within your drawable folder you can't use it in your xml file, it won't be recognized when you use android:src.
Take a look at this thread: Can the Android drawable directory contain subdirectories?