【问题标题】:(Android Xamarin) Get Resource string value instead of int(Android Xamarin) 获取资源字符串值而不是 int
【发布时间】:2013-04-09 08:33:26
【问题描述】:

我刚刚开始使用 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.&lt;key&gt; 返回一个整数,所以我不能使用上面的代码。 我希望recordTable 变量的值为records

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

【问题讨论】:

  • 只需获取int,然后将其转换为String
  • 对不起,我无法理解你的提议。

标签: android xamarin.android xamarin


【解决方案1】:

尝试使用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);

【讨论】:

  • 嗯,我看不到 GetString 方法。为了能够使用 Resources 对象,我需要添加 Android.Content.Res 命名空间。
  • @eaon21 :是的,请参阅Resources.GetString
  • 我看到了!谢谢.. 但是,我使用 Resources.System.GetString(id)... Resources.GetString 不存在 :(
  • @eaon21 : 取决于你如何调用 getString 方法
  • 我认为我没有看到 Resources.GetString() 的原因是因为我使用 C# 进行编码。我猜你必须在 C# 中使用 Resources.System.GetString()。
【解决方案2】:

值得注意的是,您确实不需要需要创建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);
    }
}

Resources,以这种方式使用,是 ContextWrapper 类的只读属性,Activity 继承自 ContextThemeWrapper 类。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:
      int int_recordTable = Resource.String.RecordsTable;
      
      String recordTable = (String.valueOf(int_recordTable)); //no more errors
      

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

      【讨论】:

      • 由于 OP 使用 Xamarin,他可能使用 .Net 而非 Java 进行编码。另外我不认为他只想将 int 转换为 String
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多