Naming convention for IDs in Android

一笑奈何 提交于 2019-12-22 10:46:26

问题


Android 2.3.3.

I have a question regarding naming the IDs in Android.

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.

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?


回答1:


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

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>

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

Update:

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).




回答2:


In my opinion when you name the IDs you should write the name of the activity that will used them first then the initial of the widget and finally whatever it's functionality is e.g. loginBSave, loginBCancel, activity2BSave, activity2BCancel anyways it totally depends on you the programmer to name them in a way that you could differentiate them from eachother

For example:

<activity_or_layout_name>_button_save
<activity_or_layout_name>_button_cancel



回答3:


Sharing the same Id between multiple activities is of no consequence and in fact, you can even have the same ID used many times in the same activity without any problem. In this case, a call to getViewById() will simply return the first View that it will find when there are many Views in the same hierarchy with the same ID.

This kind of situation usually happens when the same layout need to be inflated multiple times from its XML file. If you need to find all the View sharing the same ID, you have to change the ID of each View with a setId() one after the other after each find or give a different starting point.




回答4:


For layout specific elements I use prefix with first letters of layout name. So if I have layout named show_task_layout.xml, it's elements will have the name stl_button_ok etc.

For specific elements which may copy or appear in many activities I prefer to use one name without prefix. But If follow this way in each layout it will be a headache to debug If when you will not find an element by id



来源:https://stackoverflow.com/questions/14909719/naming-convention-for-ids-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!