[译]:Xamarin.Android应用基础——Android中的Assets资源使用
博客分类: 官方教程
返回索引目录
原文链接:Using Android Assets
译文链接:Xamarin.Android应用基础——Android中的Assets资源使用
Part 6 - Android Assets资源使用
Assets 提供了一种在应用中包含任意文件(如文本、xml、字体、音乐和视频)的方法。如果你试图将那些文件以资源方式包含到项目中,Android会将它们处理到资源系统中,那样,你将无法获取原始文件数据。如果你想访问原始的数据,Assets是一种可以处理这种情况的方法。
添加到项目中的Assets资源将会像文件系统一样显示 —— 你的应用可以通过AssetManager来读取它们。
在本示例中,我们将添加一个文本文件资源到我们的项目中,然后通过AssetManager读取它,并将它显示到TextView中。
添加一个Asset资源到项目中
Assets资源将添加到项目的Assets文件夹下。首先添加一个 新的文本文件到此文件夹,并将其 命名为read_asset.txt
。然后为其添加内容,如“I came from an asset!”。
在Visual Studio中需要设置文件的属性:将 生成操作 设置为 AndroidAsset:
选择正确的生成操作可确保文件在编译时被打包到APK中。
读取Assets资源
Assets资源读取需要使用AssetManager。通过访问Android.App.Context(如Activity)中的Assets属性来访问AssetManager的实例。
在下面代码中,我们打开“read_asset.txt”文件,然后读取内容,并将其显示到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);
}
运行应用
运行应用,你将会看到如下内容:
译:奇葩史