如何从动态创建的(Java 中)layer-list / LayerDrawable 中获取 Android 资源 ID?
此问题/答案帖子中的“解决方案#2(动态)”:
非常接近我想要做的事情,即动态创建一个图层列表(对于状态栏通知图标,我想构建我的图标层),但通知 API 中的图标分配需要资源 ID(我想从服务调用)。
我无法弄清楚如何在不构建数百个图层列表 .xml 文件的情况下动态构建图层列表(对于我希望能够显示的各种图标组合)。 Daniel 的“解决方案#1”对于静态 .xml 文件效果非常好,但我正在寻找更优雅的动态解决方案。
在上面的帖子中,代码片段:
Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.t);
layers[1] = r.getDrawable(R.drawable.tt);
LayerDrawable layerDrawable = new LayerDrawable(layers);
似乎是我想要的,但我不知道或不理解如何将新的layerDrawable“分配”给我的通知图标(它需要一个资源ID)。
感谢大家...stackoverflow 是一个很棒的资源!
The "solution #2 (dynamic)" in this question/answer post:
overlay two images in android to set an imageview
is very close to what I want to do, which is to dynamically create a layer-list (for a status bar notification icon, I want to build-up my icon in layers), but the icon assignment in the notification API requires a resource ID (which I want to call from a service).
I cannot figure-out how to build a dynamically build a layer-list without building hundreds of layer-list .xml files (for the various combinations of icons that I would like to be able to display). Daniel's "solution #1" works wonderfully for the static .xml files, but I'm looking for a more elegant, dynamic solution.
In the above post, the code snippet:
Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.t);
layers[1] = r.getDrawable(R.drawable.tt);
LayerDrawable layerDrawable = new LayerDrawable(layers);
appears to be what I want, but I don't know or understand how to "assign" the new layerDrawable to my notification icon (which takes a resource ID).
Thanks to all...stackoverflow is a wonderful resource!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用“getIdentifier”来获取它。假设我在“/res/drawable/”中有一个文件bug.png,所以我用以下代码获取它的ResourceID :
// 或
参考:
anddev.org
Use "getIdentifier" to get it.Suppose that I have a file bug.png in the "/res/drawable/", so i get its ResourceID with the following code:
// or
reference:
anddev.org
运行时创建的 Drawable 不存在 ID 之类的东西。这些 ID 引用 R 类中的 int 字段,自动从 xml 文件创建。
由于 LayerDrawable 构造函数只需要一个 Drawable 数组,因此您可以提供通过任何方法生成的那些 Drawable。例如,静态方法
Drawable.createFromStream(InputStream is, String srcName)
。http://developer.android.com/reference/android/graphics/drawable/Drawable.html#createFromStream%28java.io.InputStream,%20java.lang.String%29
There is no such thing as an ID for a Drawable created at runtime. Those IDs refer to int fields in the R class, automatically created from the xml files.
Since the LayerDrawable constructor requires just a Drawable array, you can provide those Drawables made from any method. An example, would be the static method
Drawable.createFromStream(InputStream is, String srcName)
.http://developer.android.com/reference/android/graphics/drawable/Drawable.html#createFromStream%28java.io.InputStream,%20java.lang.String%29