Android中ID的命名约定 [英] Naming convention for IDs in Android

查看:203
本文介绍了Android中ID的命名约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android 2.3.3.

Android 2.3.3.

我有一个关于在Android中命名ID的问题.

I have a question regarding naming the IDs in Android.

比方说,我在Activity1中有两个按钮(保存和取消).我将它们(ID)命名为btnSave和btnCancel.现在我有了Activity2,在其中我也有保存和取消按钮.两者具有相同的功能.如果我将ID设置为btnSave和btnCancel,将会发生什么情况.

Let's say I have two buttons in Activity1 (save and cancel). I name them (IDs) as btnSave and btnCancel. Now I have Activity2, where in I have save and cancel buttons as well. Both does the same functionality. What will happen if I give the IDs as btnSave and btnCancel.

我在编译时会遇到问题吗?当我按R.id.和Ctrl +空格键,我可以选择两个btnSave和btnCancel吗?

Will i face a problem while compiling? When I press, R.id. and ctrl+space, will I get two btnSave and btnCancel(s) to choose from?

最重要的是,如果可以的话,为什么还要命名不同?

And most importantly, Why should I name them differently, if I should?

推荐答案

如果仅是简单的代码编写方式,那么

If its only matter to easy way for writing in code, then

您可以尝试以下操作,例如(用活动或带有前缀或后缀的布局xml文件写按钮的名称)

you can try something like, (writing button's name with either activity or layout xml file with prefix or suffix)

button_save_<activity_or_layout_name>
button_cancel_<activity_or_layout_name>

但是在运行时,布局视图始终引用您的按钮ID.您已将其设置到活动"的setContentView()中.

But at run time your button id always referred by the layout view. Which you are set into your Activity's setContentView().

更新:

假设在Activity2中,您使用ID为Activity1布局的ID的按钮,那么您会得到 NullPointerException ,因为当前Activity2中未引用您的按钮. (因为您的Activity2具有不同的布局).

Suppose in Activity2 you are using button with id of Activity1's layout then you can get NullPointerException as your button is not referenced in Current Activity2. (Because your Activity2 has different layout).

这篇关于Android中ID的命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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