R.java 背后的概念是什么? [英] What is the concept behind R.java?

查看:24
本文介绍了R.java 背后的概念是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 android 中,R.java 用于提供对 XML 文件中定义的资源的访问.要访问资源,我们需要调用 findViewById() 方法,传入要获取的资源的 id.

这与 Spring 类似,其中 bean 定义在 XML 上下文中,并使用应用程序上下文获取.context.getBean("beanId")

这提供了松散耦合,因为 bean 是在外部定义的,并且可以在不修改代码的情况下进行更改.

这让我很困惑.虽然 Android 的功能看起来和 spring 很相似,但它有什么优势?

<块引用>

  1. 无论如何,拥有中间 R.java 的意义何在?难道我们不能直接通过使用资源从 XML 中获取资源吗?阅读器/应用程序上下文.例如findViewById("resourceId")
  2. 没有任何松散耦合.由于 R.java 中的引用是自动生成的,如何删除资源并放入新资源?
  3. 它遵循什么设计模式(如果有的话)?
  4. 使用 IOC(如 Roboguice)注入资源不是更好吗?为什么谷歌决定给我们这样的使用资源的奇怪方式?

请原谅我的无知.我是一个新手 Java 开发人员,同时尝试了太多东西.:-)感谢所有反馈.

解决方案

android.R.java 不仅仅是存储 XML id 的地方.它还包含对资源的访问 - 例如可绘制对象、布局、字符串、数组,以及您可以在资源中声明的任何内容.

我个人觉得它在使用 Eclipse 时很有用.我可以简单地输入 findViewById(R.id. 和 Eclipse 将显示一个工具提示,其中包含可供选择的选项列表.

然而,在平台级别,我会说硬编码的 id 变量有助于防止在使用字符串识别资源时出错——在编程时(或在编译期间,而不是在运行时)可以调试的东西.

In android R.java is used to provide access to resources defined in XML files. To access the resource we need to invoke findViewById() method passing in the id of the resource to be fetched.

This is similar to Spring where beans are defined in a XML context and are fetched by using application context. context.getBean("beanId")

This provides loose coupling since the beans are defined externally and could be changed without making modifications to the code.

This has me confused. Though what Android does looks similar to spring, what advantage does it offer?

  1. What is the point of having an intermediate R.java anyway? Couldn't we just acquire resources directly from XML by use of a resource reader/application context. e.g. findViewById("resourceId")
  2. There isn't any loose coupling. Since references in R.java get auto-generated how could one delete a resource and put in a new one?
  3. What design pattern does it follow(if there is one)?
  4. Wouldn't it be better to have resources injected using IOC (like Roboguice)? Why did then google decide to give us such a wierd way of working with resources?

Pardon my ignorance. I'm a newbie Java developer trying too many things at once. :-) Thanks for all the feedback.

解决方案

android.R.java is not just where XML ids are stored. It also contains access to resources - such as drawables, layouts, strings, arrays, and basically anything you can declare in resources.

Personally I find that it is useful when using Eclipse. I can simply type findViewById(R.id. and Eclipse will show a tooltip with a list of options to choose from.

However at a platform level, I would say that the hardcoded id variables help prevent errors when using Strings to identify resources -- something that can be debuggable while programming (or during compilation, rather than runtime).

这篇关于R.java 背后的概念是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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