为什么我必须按下按钮? [英] Why do i have to cast a Button?

查看:76
本文介绍了为什么我必须按下按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这肯定是一个非常愚蠢的问题,因为我无法在线找到答案...。我知道强制转换将一种数据类型更改为另一种数据类型。这个按钮如何改变它的数据类型? Button button =(Button)findViewById(R.Bla.Bla)为什么我们不能只写 Button button = New Button()然后将xml分配给它另一种方式?请解释,我迷路了。

This must be a really dumb question because I cant find an answer online.... I know that casting is changing one datatype to another. How is this button ever changing it's data dype? Button button = (Button)findViewById(R.Bla.Bla) Why cant we just write Button button = New Button() And then assign the xml to it another way? Please explain, I'm lost.

推荐答案

在Android中查看您可以通过两种方式创建UI元素:

1。通过布局(.xml)文件创建UI元素。
并在Java类中使用它们可以将它们映射到相应的类。
为此,我们必须调用findViewById(int id);方法。它返回具有给定id的那个perticuler元素的视图,因此我们必须将其类型转换为相应的组件。
因此,如果您已经在xml中创建了一个元素,为什么还要在java端再次创建一个不同的对象。因此只需映射用xml文件创建的元素。

1. create UI elements through layouts (.xml) files. And to use them in java class map them to their corresponding class. And to do so we have to call method findViewById(int id); which returns the view of that perticuler element with given id.and thus we have to type cast it to respective component. And thus if you have created a element already in xml why will you create a different object again at java end. so just map the element created with xml file.

2。通过Java结束创建UI元素。
要使用此功能,必须使用新关键字ex在Java中创建元素。按钮button = new Button();然后在该对象上设置所有属性。

2. crate UI elements through java end. To use this feature use have to create the elements in java with new keywords ex. Button button = new Button(); and then set the all properties on that object.

但是,但是,但是,
根据android哲学,您应该在xml中创建UI ,并在Java端编写您的核心业务逻辑。有了这个概念,您就可以编写简洁明了的应用程序代码。
但是只建议一点都不强制。现在由您决定。...
,我认为开始时您会感觉与众不同,但是一段时间之后,您将开始爱上它...

But But But, According to android philosophy you should create UI in xml, and write your core business logic in java end. And with this concept you can write neet and clean application code. But it is only recommended not compulsory at all. now its up to you.... and i think at starting you feel it different but after some time you will start loving it...

谢谢。希望我能彻底回答您的问题。

Thanks. i hope, i answered your question throughly.

这篇关于为什么我必须按下按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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