2011-08-11 18 views
2

我在我的Drawable-mdpi文件夹中有一个名为(my_image.png)的图像。如何从Value获取Resource.Id?

我的android应用程序与web服务进行交互。它可能会发回“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但什么也没做。

+0

我想我找出了为什么你最后一个示例行不起作用。 '字符串'应该是'字符串' – gtcompscientist

回答

5

的问题是双重的:

  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"); 

对于[email protected]用户,看到 How to use Resources.GetIdentifier()线程和followup message

+0

我发现使用包名称,因为你(“MonoAndroidApplication2.MonoAndroidApplication2”)没有工作。我不得不改变它两个不同的子字符串,例如:“MonoForAndroid.MonoAndroidApplication2” –

+0

如果我需要访问像'com.android.internal.R.string.ime_action_done'这样的东西怎么办? –

3

你只需要正确地格式化您的要求:

相反的:

int i = this.getResources().getIdentifier("txt_asecondtext", "strings", this.getPackageName()); 

尝试:

int i = getResources().getIdentifier("[fully qualified package]:drawable/[resource name]", null, null); 

所以对于Resource “my_image” 中包 “com。示例” 它看起来像:

int i = getResources().getIdentifier("com.example:drawable/my_image", null, null); 

更新:我还测试了以下几项工作形成了我(包括证明它的日志行:

int i = getResources().getIdentifier(
    getPackageName() + ":drawable/" + resource_name, null, null); 
Log.d("EXAMPLE", "Just making sure that these IDs match: '" + i + "' == '" + R.drawable.resource_name + "'."); 

像上面一样这也被格式化,我相信我已经指出你的错误: getIdentified(resource_name,“drawable”,getPackageName());

+0

没有,似乎没有做任何事情。仍然打印出零。 – chobo2

+0

我刚刚在我自己的代码中测试了它,它的工作原理,让我们确保我们以相同的方式配置它。你能用你现在正在尝试的行更新你的问题吗? – gtcompscientist

+1

确保不要使用“Resources.getSystem()。getIdentifier(name,defType,defPackage)”,但使用当前上下文中的Resources对象。 –

1

对于字符串的ressource我这样做:

String s = "nameToFetch"; 
String text = getString(getResources().getIdentifier("str_" + s, "string", getPackageName())); 

因此,我认为你绘制你应该叫:

String s = "nameToFetch"; 
Drawable drawable = getDrawable(getResources().getIdentifier("d_" + s, "drawable", getPackageName())); 
相关问题