VISUAL STUDIO   Windows Mac

Using Android Assets

PDF for offline use
Related APIs:

Let us know how you feel about this

Translation Quality


0/250

last updated: 2017-03

Assets provide a way to include arbitrary files like text, xml, fonts, music, and video in your application. If you try to include these files as "resources", Android will process them into its resource system and you will not be able to get the raw data. If you want to access data untouched, Assets are one way to do it.

Assets added to your project will show up just like a file system that can read from by your application using AssetManager. In this simple demo, we are going to add a text file asset to our project, read it using AssetManager, and display it in a TextView.

Add Asset to Project

Assets go in the Assets folder of your project. Add a new text file to this folder called read_asset.txt. Place some text in it like "I came from an asset!".

Visual Studio should have set the Build Action for this file to AndroidAsset:

Setting the build action to AndroidAsset

Xamarin Studio should have set the Build Action for this file to AndroidAsset:

Setting the build action to AndroidAsset

Selecting the correct BuildAction ensures that the file will be packaged into the APK at compile time.

Reading Assets

Assets are read using an AssetManager. An instance of the AssetManager is available by access the Assets property on an Android.App.Context, such as an Activity. In the following code, we open our read_asset.txt asset, read the contents, and display it using a TextView.

protected override void OnCreate (Bundle bundle)
{
    base.OnCreate (bundle);

    // Create a new TextView and set it as our view
    TextView tv = new TextView (this);

    // Read the contents of our asset
    string content;
    AssetManager assets = this.Assets;
    using (StreamReader sr = new StreamReader (assets.Open ("read_asset.txt")))
    {
        content = sr.ReadToEnd ();
    }

    // Set TextView.Text to our asset content
    tv.Text = content;
    SetContentView (tv);
}

Running the Application

Run the application and you should see the following:

Example screenshot

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.