在我开始使用Xamarin Android开发的应用程序中,我有一个Lyrics菜单选项。单击后,它将启动一个名为“歌词”的新活动,该列表中将存在一个listView,其中应填充可点击的行,这些行具有Assets文件夹中的txt文件的标题。
因此,如果Assets文件夹中有3个lyricsX.txt文件,则listView看起来像这样:
[ lyrics1.txt ]
[ lyrics2.txt ]
[ lyrics3.txt ]
这些带有歌词标题的按钮应该可以点击。
我试图将路径放入字符串文件中,然后使用Directory.EnumerateFiles ..然后在其中进行遍历并将结果写入调试控制台,但未记录任何内容。可能我的方法错误,只是我不知道我在做什么错。
[Activity(Label = "Lyrics")]
public class Lyrics : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
string assetsPath = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath;
var assetsContents = Directory.EnumerateFiles(assetsPath);
TextView title = FindViewById<TextView>(Resource.Id.lyricsTitle);
foreach(var fileName in assetsContents)
{
Log.Debug("debug", "NAME:" + fileName);
}
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.lyrics);
}
}
答案 0 :(得分:1)
当然,您可以...这将向您展示如何从Assets文件夹访问文件以及将文件加载到具有可点击结果的ListView中的方法。
main_layout.axml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/lvAssetFiles"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:layout_weight="1"
android:background="@android:color/transparent" />
</RelativeLayout>
MainActivity.cs
using System.Collections.Generic;
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Widget;
namespace ListViewExample {
[Activity(Label = "ListView Example", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
public class MainActivity : AppCompatActivity {
private ListView lvFiles;
private List<string> lstFiles = new List<string>();
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.main_layout);
// To get all .txt files in the Assets root folder...
var listAssets = Assets.List("");
foreach (var file in listAssets) {
if (file.EndsWith(".txt"))
lstFiles.Add(file);
}
// To get all files in the Assets/Lyrics folder...
//listAssets = Assets.List("Lyrics");
//foreach (var file in listAssets)
// lstFiles.Add(file);
var adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, lstFiles.ToArray());
// Or, use this to keep the item highlighted after clicking
//var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItemActivated1, lstFiles.ToArray());
lvFiles = FindViewById<ListView>(Resource.Id.lvAssetFiles);
lvFiles.Adapter = adapter;
lvFiles.ItemClick += lvFiles_ItemClick;
lvFiles.ChoiceMode = ChoiceMode.Single;
}
private void lvFiles_ItemClick(object sender, AdapterView.ItemClickEventArgs e) {
var sItemSelected = lstFiles[e.Position];
Android.Util.Log.Info("MyApp", $"Item Selected: {sItemSelected}");
}
}
}
此外,请确保“构建操作”的“资产”文件夹中的每个文件都设置为“ AndroidAsset”。
干杯!