Main.axml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/MyButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="讀取 Asset 圖片" /> <TextView android:text="Text" android:layout_width="match_parent" android:layout_height="100.0dp" android:id="@+id/textView1" /> <ImageView android:src="@drawable/xamarinicon" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/imageView1" android:layout_marginTop="0.0dp" android:layout_marginBottom="0.0dp" /> </LinearLayout>
MainActivity.cs
using System.IO; using System.Text; namespace ImageViewAssets { [Activity(Label = "ImageViewAssets", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); Button button = FindViewById<Button>(Resource.Id.MyButton); ImageView image = FindViewById<ImageView>(Resource.Id.imageView1); TextView text = FindViewById<TextView>(Resource.Id.textView1); button.Click += (Sender, e) => { string TargetPath = @"DemoDir/DemoDir2"; string[] result = Assets.List(TargetPath); // 產生隨機整數 Random r = new Random(Guid.NewGuid().GetHashCode()); int IndexID = r.Next(0, result.Length); string fileName = result[IndexID].ToString(); string fileFullName = Path.Combine(TargetPath, fileName); string fileDriodFullName = Path.Combine(FilesDir.Path, fileName); StringBuilder builder = new StringBuilder(); builder.AppendLine($"Aseet 檔案名稱:{fileName}"); builder.AppendLine($"Asset 檔案完整路徑:{fileFullName}"); builder.AppendLine($"Driod 檔案完整路應:{fileDriodFullName}"); text.Text = builder.ToString(); using (var stream = Assets.Open(fileFullName)) using (var file = File.Create(fileDriodFullName)) { stream.CopyTo(file); } image.SetImageURI(Android.Net.Uri.Parse(fileDriodFullName)); }; } } }
- Asset
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.原以為 Asset 會如同 Drawable 一樣可以透過 Reflection 來取得裡面的檔案,沒想到 Asset 不是 Class,Asset 內資料是存在 APK 內,要透過 AssetManager 來取得
Assets added to your project will show up just like a file system that can read from by your application using AssetManager.
1 則留言:
非常謝謝您的分享,清楚明瞭!
張貼留言