FindViewById() 如何工作? [英] How does FindViewById() work?

查看:33
本文介绍了FindViewById() 如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Button button = FindViewById

所以我试图以同样的方式创建我自己的按钮.我在设计器中创建按钮,并在 OnCreate 方法中放置一行:

Button myOwnBtn = FindViewById

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

public const int MyButton=2123344112;

如果我把这条线放在那里:

public const int MyOwnBtn=2123344113;

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

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

解决方案

你必须把 id MyOwnBtn 给你的 Button在设计器中创建.

findViewByIdView 类的一个方法,它查找具有您在参数中提供的 id 的子视图.

来自官方文档:><块引用>

查找具有给定 ID 的子视图.如果此视图具有给定的 id,则返回此视图.

I'm new in mobile app development. I'm using Xamarin to develop Android applications. In the hello world app in the OnCreate method I see the following code:

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

So I'm trying to create my own button the same way. I create the button in the designer and inside OnCreate method put the line:

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

That gives me an error that there is no MyOwnBtn. Then I'm looking the code of Id class and see there a line like:

public const int MyButton=2123344112;

If I put there the line:

public const int MyOwnBtn=2123344113;

Everything works fine. But as I understand it should be generated automatically or it will be a little bit difficult to put there a unique number for each control.

Can anybody tell me what I am doing wrong? And how does FindViewById() work?

解决方案

You have to give the id MyOwnBtn to the Button that you created in the designer.

findViewById is a method of the View class and it looks for a child view having the id that you provided in the argument.

From official documentation:

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

这篇关于FindViewById() 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆