【问题标题】:Creating a List<String> in Android Xamarin在 Android Xamarin 中创建 List<String>
【发布时间】:2014-02-10 17:16:08
【问题描述】:

我正在构建一个 Android 应用程序,我需要在其中创建一个简单的字符串项目列表,然后我将为列表中的每个项目添加一个特定的控件。

这是我要创建的列表:

List<String> projects = new List<String>(); // How?

我正在尝试的代码:

String projects = new string[] { "hey","yo","app","xamarin","c","xaml" };

我需要清点物品,如下所示:

int amount = projects.Count(); // Can I do this?

然后为列表中的每个项目添加控件

// Add the tiles, one by one
for (int i = 0; i < amount; i++)
{
  // Inflate the tile
  var tile = LayoutInflater.Inflate (Resource.Layout.Tile, null);

  // Set its attributes
  tile.FindViewById<TextView> (Resource.Id.projectName).Text = currentProject;

  // Add the tile
  projectScrollView.AddView (tile);
}

"currentProject" 字符串是从 SharedPreferences 中检索到的,还没有到那么远

【问题讨论】:

  • 你有什么问题?
  • @HighCore 听起来像是关于语法的问题
  • 这是关于我如何创建一个基本的字符串列表,轻松添加、读取和删除项目并能够对它们进行计数

标签: c# android list dynamic for-loop


【解决方案1】:
   var projects = new List<String>() { "hey","yo","app","xamarin","c","xaml" };

【讨论】:

  • 我正在尝试使用此代码,但未找到“列表”。只是得到一个错误。它是什么导入/使用?
  • System.Collections.Generic;
【解决方案2】:

如果您使用数组来存储列表中所需的值,请使用 foreach

List<string>project = new List<string>();
string[] projects = { "hey","yo","app","xamarin","c","xaml" };

foreach(string str in projects)
{
   project.Add(str);
}
for (int i = 0; i < projects.Length; i++)
{
  // Inflate the tile
  var tile = LayoutInflater.Inflate (Resource.Layout.Tile, null);

  // Set its attributes
  tile.FindViewById<TextView> (Resource.Id.projectName).Text = currentProject;

  // Add the tile
  projectScrollView.AddView (tile);
}   

// you can get items from your list by using  project.Count, your List<string> instead of projects.Length your array and take information from your list and output your tiles that way

【讨论】:

  • 除了,不,您应该使用.AddRange 并避免循环和数组调整大小。
  • 但是当我键入 List 时未检测到它。我需要添加“使用”行吗?
  • 你现在在“使用”什么?如果它是未知的,很难说你是否有它。
  • List&lt;T&gt;System.Collections.Generic 的一部分
【解决方案3】:

要使用collection initializer 初始化List&lt;string&gt;,请使用以下语法。

List<String> projects = new List<String>(){"hey","yo","app","xamarin","c","xaml"};

Count 不是方法而是属性。您需要属性语法。

int amount = projects.Count;

【讨论】:

  • 你不能离开new List&lt;String&gt;()吗?我知道括号至少是额外的。
  • @Magus 是的,这是可选的。但我相信它会创建一个数组而不是列表。除了需要括号休息
【解决方案4】:
int amount = projects.Length; 

这就是设置 int 值的方法。您似乎没有使用该代码填充您的列表。

【讨论】:

    猜你喜欢
    • 2020-03-10
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2021-09-04
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    相关资源
    最近更新 更多