(Android Xamarin)获取资源字符串值而不是int

时间:2013-04-09 08:33:27

标签: android xamarin.android xamarin

我刚刚开始使用VS2012使用Xamarin创建一个简单的Android应用程序。 我知道有一种资源只用于字符串。 在我的资源文件夹中,我有一个像这样的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="RecordsTable">records</string>
   <string name="ProjectTable">projects</string>
   <string name="ActivitiesTable">activities</string>
</resources>

在我的代码中,我想使用这些资源的值,如:

string recordTable = Resource.String.RecordsTable; //error, data type incompatibility

我知道Resource.String.<key>返回一个整数,所以我不能使用上面的代码。 我希望recordTable变量的值为records

有没有办法可以将这些资源字符串的值用于我的代码的字符串变量?

4 个答案:

答案 0 :(得分:35)

尝试使用Resources.GetString从字符串资源中获取字符串

Context context = this;
// Get the Resources object from our context
Android.Content.Res.Resources res = context.Resources;
// Get the string resource, like above.
string recordTable = res.GetString(Resource.String.RecordsTable);

答案 1 :(得分:13)

值得注意的是,需要创建Resources的实例才能访问资源表。这同样有效:

using Android.App;

public class MainActivity : Activity
{
    void SomeMethod()
    {
        string str = GetString(Resource.String.your_resource_id);
    }
}
以这种方式使用的

GetString()是在抽象Context类上定义的方法。您也可以使用此版本:

using Android.App;

public class MainActivity : Activity
{
    void SomeMethod()
    {
        string str = Resources.GetString(Resource.String.your_resource_id);
    }
}
以这种方式使用的

ResourcesContextWrapper类的只读属性,Activity继承自ContextThemeWrapper类。

答案 2 :(得分:3)

如果您不在活动或其他上下文中,则应获取上下文并使用它来获取Resources和PackageName,如下例所示:

int resID = context.Resources.GetIdentifier(listEntryContact.DetailImage.ImageName, "drawable", context.PackageName);
imageView.SetImageResource(resID);

答案 3 :(得分:-5)

int int_recordTable = Resource.String.RecordsTable;

String recordTable = (String.valueOf(int_recordTable)); //no more errors

获取int,然后将其更改为String

相关问题