android - 如何从 Value 中获取 Resource.Id?

标签 android xamarin.android

我的 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,但没有任何作用。

最佳答案

问题是双重的:

  1. 您需要在 Resources.GetIdentifier() 调用中提供包名称,而不是使用 null
  2. 您需要使用正确的包名。

确保获得正确包名称的简单方法是使用 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/

相关文章:

android - kotlin setter 无限递归

android - SQLite 数据库锁定读取

xamarin - 在类中请求 Android 权限 (Xamarin)

java - 将用户在 TimePicker 中选择的所有值放入列表中并读取它

java - 如何在 Google Play 测试/实时中为应用程序设置不同的端点?

java - onActivityResult 有效!但我无法调试

c# - 使用 Azure IOT 库创建 Xamarin.Forms .Net Standard 应用程序?

android - Xamarin:找不到 "libmonodroid.so"模拟器错误

c# - 如何在c#中将GPS时​​间从android转换为本地时间

c# - 如何将 android Unity 错误和调试日志导出到文件?