27

Im just starting to create a simple android app with the use of Xamarin using VS2012. I know there is a type of Resource just for strings. In my resource folder, i have an xml file like this:

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

In my code, I want to use the values of those resources like:

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

I know that Resource.String.<key> returns an integer so I cant use the code above. I am hoping that recordTable variable will have a value of records.

Is there a way I can use the value of those resource string for my code's string variables?

raberana
  • 11,870
  • 18
  • 62
  • 89

4 Answers4

39

try it as using Resources.GetString for getting string from string Resources

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);
ρяσѕρєя K
  • 127,886
  • 50
  • 184
  • 206
13

It's worth noting that you do not need to create an instance of Resources to access the resource table. This works equally well:

using Android.App;

public class MainActivity : Activity
{
    void SomeMethod()
    {
        string str = GetString(Resource.String.your_resource_id);
    }
}

GetString(), used this way, is a method defined on the abstract Context class. You can also use this version:

using Android.App;

public class MainActivity : Activity
{
    void SomeMethod()
    {
        string str = Resources.GetString(Resource.String.your_resource_id);
    }
}

Resources, used this way, is a read-only property on the ContextWrapper class, which Activity inherits from the ContextThemeWrapper class.

Tieson T.
  • 20,030
  • 4
  • 69
  • 86
3

If you're not in an activity or another context, you should get the context and use it to get the Resources and PackageName, as the following example:

int resID = context.Resources.GetIdentifier(listEntryContact.DetailImage.ImageName, "drawable", context.PackageName);
imageView.SetImageResource(resID);
da Rocha Pires
  • 2,198
  • 20
  • 18
-5
int int_recordTable = Resource.String.RecordsTable;

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

Get theint, then change it to a String

Bigflow
  • 3,526
  • 5
  • 26
  • 52