Reputation: 11109
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?
Upvotes: 5
Views: 7164
Reputation: 331
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
Upvotes: 4
Reputation: 3938
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.
Upvotes: 1
Reputation: 507
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
Upvotes: 0
Reputation: 109237
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).
Upvotes: 6