Forum Xamarin.Android

Get ID of variable resource

I've found several posts about getting the ID of a resource by name. I have tried two different methods, and never one works.

//This one returns 0:
int varInt = Resources.GetIdentifier ("background1", "drawable", PackageName);

//This one returns 'object reference not set':
int varInt = (int)typeof(Resource.Layout).GetField("background1").GetValue(null);

Am I doing something wrong? I have several drawable folders (i.e. drawable-land, drawable-port, etc.), but I tried using drawable-land in the above code and it still returns 0. Thanks!

Posts

  • MatthewHoltzMatthewHoltz USMember
    edited January 2014

    I found that it works for one drawable, but not another. Both are in the drawable-land folder. Yes, I double checked the spelling.

  • DirkMaasDirkMaas USMember ✭✭
    edited August 2014

    I know this is months late, but I've found that Resources.GetIdentifier is erratic. Works with some resources, but not others. No rhyme or reason (that I can figure out). But if the resource you're looking for is in drawable-land, the 2nd arg in the first call should be "drawable-land". And in the 2nd call, Resource.Layout should be Resource.Drawable-Land (not sure about the capitalization). I'm using the 2nd form, as it is reliable. More info here and here.

  • DirkMaasDirkMaas USMember ✭✭

    Correction: Instead of "Drawable-Land" simply use "Drawable". I have not specifically tested getting a resource ID from the drawable-land folder, but the following line found the requested resource even though it was not in "Drawable" but "drawable-mdpi".

    var resID2 = (int)typeof(Resource.Drawable).GetField("ic_action_cancel").GetValue(null);

    I can't find it in the documentation, but it looks like the system knows which drawable-xxxx folder to look in.

    I'm sure this is too late for Matthew, but maybe it will help someone else.

  • burf2000burf2000 GBMember

    I am trying to load a android drawable via forms. The image mario is in all of the drawable folders.

    I have tried
    var resID2 = (int)typeof(Resource.Drawable).GetField(name).GetValue(null);

    and
    int id = GetId (typeof(Android.Resource.Drawable), name);

    both do not work, file is marked as Android resource

  • azulahazulah USMember
    edited July 2016

    Its work for me.

    /* GetField("case_sensitive.png") .png name is case sensitive , once your icon name is not match it will throw an exception so in this case we use .ToString().ToLower() , make sure that your icon file name is all lower case.
    */
    int resourceId = (int)typeof(Resource.Drawable).GetField(item.Icon.ToString().ToLower()).GetValue(null);

Sign In or Register to comment.