Xamarin:以编程方式为 TextView 设置文本

Xamarin: Setting text for a TextView programmatically

这可能是我的错误或缺乏理解,但我现在很困惑。我正在尝试以编程方式在我的 Xamarin Android 应用程序中设置一个 TextView。这是我的代码:

TextView currentCharacterName = FindViewById(Resource.Id.characterName); currentCharacterName.SetText("test");

不幸的是,这不起作用,因为我收到错误 "Argument 1: cannot convert from 'string' to 'int'"。在阅读了 SetText 的可用方法后,我注意到我尝试调用的方法需要一个 ResId。我真的不明白为什么我需要一个 ResId 来修改 TextView 的文本。

我尝试在 Google 上搜索答案,然后我遇到了 2014 年的 this answer,它与我遇到的问题完全相同。解决方案是使用 Text() 方法代替设置 TextView。不幸的是,当我尝试这个解决方案时,我得到了错误 "Non-invocable member 'TextView.Text' cannot be used like a method"。当我尝试检查 Text 方法描述时,我看到 "string TextView {get/set} To be added."

这是否意味着还没有实现来设置 TextView 的文本?我真的不愿意相信这一点,因为让我感到困惑的是像Xamarin这样的大框架甚至没有get/set功能来设置TextView的文本这样简单的事情。我觉得我的问题有一个非常简单的解决方案,但我似乎找不到它。

TextView.SetText(X) 允许您设置来自资源 ID 的文本:

currentCharacterName.SetText(Resources.Id.MyString);

您正在寻找 Text 属性:

currentCharacterName.Text = "test";

赛马林:TextView class

Android.Widget.TextView.Text Property

Syntax:

public String Text { get; set; }

测试这段代码:

TextView currentCharacterName = FindViewById<TextView>(Resource.Id.characterName);
currentCharacterName.Text = "Your Text";