Archive for December, 2013

Xamarin Studio Android – adding assets and resources

Thought I would write a TL;DR as I found the information online lacking or too elaborate. The example here is with images; other types are similar obviously.

Assets:

Setup:

  • copy/drag your asset into the Assets directory
  • right-click => Build Action->AndroidAsset

Retrieve in code:

                                                Stream istr;

   Bitmap bitmap = null;
try {
    istr = Assets.Open("some-image.jpg");
bitmap = BitmapFactory.DecodeStream(istr);

} catch (IOException e) {
//something went wrong
}

It can now be used with ImageView.SetImageBitmap() for instance.

Resources: 

Setup:

  • copy/drag your file into the Resources directory 
  • right-click => Build Action->AndroidResource 
Please note ; the naming of resources is particular and you’ll get no errors if you do it wrong (nice he!); you cannot  use dashes(-) etc; you’ll notice you did it right when you see Resource.designer.cs change; it’ll have the reference to your file in it. 
Use resources by referencing them in the project code; if you have a project MyCompany.MyProject, you can reference it by; MyCompany.MyProject.Resource.Drawable.MyImage and use something like ImageView.SetImageResource( MyCompany.MyProject.Resource.Drawable.MyImage );