如何从Value获取Resource.Id?

cho*_*bo2 2 android xamarin.android

我的Drawable-mdpi文件夹中有一个名为(my_image.png)的图像.

我的android应用程序与webservice交互.它可能会发回"my_image".我的Android应用程序应该加载此图像.

我正在使用Monodroid,我试过这个

   int abc = Resources.GetIdentifier("my_image","drawable",null);
Run Code Online (Sandbox Code Playgroud)

但结果总是如此"0".什么时候应该(从资源文件)

        // aapt resource value: 0x7f020000
        public const int my_image = 2130837504;
Run Code Online (Sandbox Code Playgroud)

环顾四周,android方式似乎相似

int i = this.getResources().getIdentifier("txt_asecondtext", "strings", this.getPackageName());
Run Code Online (Sandbox Code Playgroud)

我尝试传递包名称而不是null但没有做任何事情.

jon*_*onp 5

问题是双重的:

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

确保获得正确包名的简单方法是使用Android.Content.Context.PackageName属性:

int id = Resources.GetIdentifier ("my_image", "drawable", PackageName);
Run Code Online (Sandbox Code Playgroud)

如果您不想/不能使用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>
Run Code Online (Sandbox Code Playgroud)

因此,您可以改为使用:

int id = Resources.GetIdentifier ("my_image", "drawable", 
        "MonoAndroidApplication2.MonoAndroidApplication2");
Run Code Online (Sandbox Code Playgroud)

对于monodroid@lists.ximian.com订阅者,请参阅如何使用Resources.GetIdentifier()线程和后续消息.