c# - FindViewById() 如何工作?

标签 c# android xamarin xamarin-studio

我是移动应用开发新手。我正在使用 Xamarin 开发 Android 应用程序。在 hello world 应用程序的 OnCreate 方法中,我看到以下代码:

Button button = FindViewById<Button>(Resource.Id.MyButton);

所以我尝试以同样的方式创建我自己的按钮。我在设计器中创建按钮,并在 OnCreate 方法中添加以下行:

Button myOwnBtn = FindViewById<Button>(Resource.Id.MyOwnBtn);

这给了我一个错误,没有 MyOwnBtn。然后我查看 Id 类的代码,看到这样一行:

public const int MyButton=2123344112;

如果我把这行放在那里:

public const int MyOwnBtn=2123344113;

一切正常。但据我了解,它应该自动生成,否则为每个控件放置一个唯一的编号会有点困难。

谁能告诉我我做错了什么? FindViewById() 是如何工作的?

最佳答案

您必须将 id MyOwnBtn 提供给您在设计器中创建的 Button

findViewByIdView 类的一种方法,它会查找具有您在参数中提供的 id 的 subview 。

来自official documentation :

Look for a child view with the given id. If this view has the given id, return this view.

关于c# - FindViewById() 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25278612/

相关文章:

c# - 无法将类型 'bool?' 隐式转换为 'bool' 。存在显式转换(您是否缺少转换?)

android - android 上的 Scala Actor

Android:根据颜色检查谷歌地图标记是否存在

c# - Xamarin -> System.Reflection.Assembly.GetExecutingAssembly 不起作用

C# oledexception

c# - 如何通过命令提示符调用 MSBuild?

ios - 某些功能在 "Release"部署中不起作用(但在 "Debug"中起作用)

visual-studio - Xamarin - 如何将启动屏幕图像居中(iOS)?

javascript - 将 TCP 监听器或 HTTP 监听器与 IIS 一起使用

Android:如何使用简单适配器将图像文件从 sd 卡放入 HashMap?