我的 Drawable-mdpi 文件夹中有一个名为 (my_image.png) 的图像。
我的 android 应用程序与网络服务交互。它可能会发回“my_image”。我的 android 应用程序应该加载此图像。
我正在使用 Monodroid,我试过了
int abc = Resources.GetIdentifier("my_image","drawable",null);
然而结果总是"0"
。应该在什么时候(来自资源文件)
// aapt resource value: 0x7f020000
public const int my_image = 2130837504;
环顾四周,android的方式似乎很相似
int i = this.getResources().getIdentifier("txt_asecondtext", "strings", this.getPackageName());
我尝试传入包名而不是 null
,但没有任何作用。
最佳答案
问题是双重的:
- 您需要在
Resources.GetIdentifier()
调用中提供包名称,而不是使用null
。 - 您需要使用正确的包名。
确保获得正确包名称的简单方法是使用 Android.Content.Context.PackageName属性:
int id = Resources.GetIdentifier ("my_image", "drawable", PackageName);
如果您不想/不能使用 Context.PackageName
,请查看构建输出,例如obj\Debug\android\AndroidManifest.xml
文件,并使用 /manifest/@package
属性值的值。例如,AndroidManifest.xml
可能包含:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0"
package="MonoAndroidApplication2.MonoAndroidApplication2">
<!-- ... -->
</manifest>
因此,您可以改用:
int id = Resources.GetIdentifier ("my_image", "drawable",
"MonoAndroidApplication2.MonoAndroidApplication2");
对于 monodroid@lists.ximian.com
订阅者,请参阅 How to use Resources.GetIdentifier()线程,以及 followup message .
关于android - 如何从 Value 中获取 Resource.Id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7030395/