as android assets,Using Android Assets

Using Android Assets

03/13/2018

2 minutes to read

In this article

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:

ec254fd2bc6013b8c5afb77c712d49bb.png

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

AndroidAsset:

6abf8cb38f4254ec5420909ef4a5d333.png

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 accessing the

Assets property on an

Android.Content.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);

}

Reading Binary Assets

The use of StreamReader in the above example is ideal for text assets. For binary assets, use the following code:

protected override void OnCreate (Bundle bundle)

{

base.OnCreate (bundle);

// Read the contents of our asset

const int maxReadSize = 256 * 1024;

byte[] content;

AssetManager assets = this.Assets;

using (BinaryReader br = new BinaryReader (assets.Open ("mydatabase.db")))

{

content = br.ReadBytes (maxReadSize);

}

// Do something with it...

}

Running the Application

Run the application and you should see the following:

62fbcc809b936c411c7eedef27c57553.png

Related Links

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值