Naming convention for IDs in Android

三世轮回 提交于 2019-12-05 19:20:24

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

amateur programmer

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

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.

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

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