Android XML id best practice - android

Suppose I have an Activity, for which I set the content view from a XML file.
Let's say I have a button, acceptButton, in the Java code.
acceptButton =(Button)findViewById(R.id.acceptBtn);
In the above code, the Java name and the XML id are different. Is there a "best practice" or standard for naming widgets? For example, should the XML id be called acceptButton too, instead of acceptBtn? It seems trivial, but it annoys me what other people do, when they give the Android name and XML id completely different names.

There is no recommendation from Google about naming resources in xml files. Also checking Code Style Guidelines for Contributors you find no mention about it, so the best would be taking a look in the SDK where you can see Google is not consistent in identifier naming.
Across the SDK you can find conventions as follow:
mHeaderText = (TextView) view.findViewById(R.id.headerText);
mHeaderText = (TextView) view.findViewById(R.id.header_text);
mHeaderText = (TextView) view.findViewById(R.id.HeaderText);
What I recommend is to be consistent per project. Decide for one naming convention and use it across the entire project.

It is never mandatory that Java name and XML id should be same. And I don't think that there are any such naming standards provided by Google. But it is seems very good practice if both of them are same. By keeping them same, we can easily identify the control by name only when there are more than one controls.
Other way is you can define a naming style of java name and XML id and follow same for all the controls. But it is developer or project specific.

It is never mandatory as Nirav said but having same name for id and Variable is good practice i always do this. This thing saves your time you don't need to remember different name for Id in xml and variable in code and also you just copy and paste after defining it in xml to code.

I would interpret it more colsely to Java conventions: "AcceptBtn" to point a class, "acceptBtn" to point an instance, "accept_btn" - others. "id" is more like an instance, definetely not a class. At least others. But I would prefer it as an instance.
R.id.AcceptBtn // As a class.
R.id.acceptBtn // As an instance.
R.id.accept_btn // Other cases.
Also as per Steve McConnel's "Code Complete" acceptBtn is more preferable to be written as acceptButton. It is more readable and less writable, but we read code more often than write it. So readable code saves more time.

Related

Android xml id naming

There are some questions about naming id in xml layout.
If i have a Activity used to create student.
What is the most suitable id for the EditText of student name?
et_student_name
et_name
et_create_student_name
I always use 3, because it is relate to the class name.But sometimes i think it is too long. I want to use 2 / 3, it is shorter but i am afraid it will repeated with other xml.
What is the good naming for the id?
Is it not good on repeated id in different xml layout?
Waiting for Help,
Thank you.
First, unless you are creating a distributed "jar" or "SDK" then you will discover name conflicts at build time. Worry about it then, not now. You are spending more time trying to avoid the problem than it's worth. Sometimes you need to prevent problems, but this isn't one of them.
If you are still worried, then there are 2 prefixes you can consider using. First, add a prefix that is somewhat descriptive of the XML file that has the element. For example, if the XML file is called "create_student.xml" then add "cs_" as the element for the prefix. (FYI - This really sucks when you change the filename, but that rarely happens.)
Second, add a prefix (or another prefix) for the package/class you are targeting. This prevents duplicates for SDK's and other libraries that may end in another developer's build. For example, if your SDK is "Student Registration and Identification" then add "sri_" to each element in the package.
The rest of the name is solely up to you. Having "et_" in the name for an EditText is helpful, the rest is going to be either "too long" or "not enough" almost every time.
to add to #AjayP.Prajapati your ids should not be the same as java keywords like break,continue ,switch,for etc..., and also your ids do not need to be special. if you have repeated ids the first occurrence will be returned.

Android coding good habit examples?

Ive been searching the internet for a while now but cant find a good page for good habit examples in android programming. For examples im interested in things like how to name classes or xml files (what case letters, where to use _) and also in file things like naming variables and fields or edittexts, prefixes and everything like that.
If someone could help me with a link i would be very grateful!1
Android developers has its answer for this.
If you need anything elaborated I'll update my answer from your comments :-)
For Classes use Java naming convention:
First letter capitalized, no "_" in the class names but start with capitalized letter for each new word ei:
MyActivity or MySettingsActivity
For xml object naming you have some other limitations as in, first letter cannot be capitalized, therefor I suggest your either use the general java naming convention for methods (First letter decapitalized, and then new words capitalized like: buttonQuit or quitButton), if it should be button first or last is up to you, but stick with 1 style. don't name 1 item: nameTextView (or nameTxtVw) and then something else buttonSubmit (Have the indicators in the same orders).
For xml files, use lower case separated with underscore "_".
Why a lot java files are called Activity in the end. It is to describe in the name that they inherit from from the superclass "Activity". It is a principle that came became big with Android, which uses it a lot, examples if these classes are inherited:
(super class = end of their heirs name)
AsyncTask = Task
Service = Service
Activity = Activity
Handler = Handler
I could go on :)
For xml files, belonging to activities I personally like to call them the name before Activity, so MainActivity's xml layout would be main.xml
If you are looking for some coding guidelines, have a look at Code Style Guidelines for Contributors
If you want to enforce this rules without remembering all of them, and you are using eclipse then you can use formatting rules provided by Android team: android-formatting.xml. Just import it into eclipse using Preferences->Java->Code Style->Formatter, click Import.
You should learn Java code conventions, and so read this:
java style
It's good to practice always name classes upper camel style (e.g CustomerService)
Class names should be noun,
For naming variables you should use lower Camel Style (e.g myVariable)
Xml file shoudl be lower case and words should be separated by under score
please read the above links!
[Edited] this part added after the first comment!
I don't know any good reference for good naming convention and things like this but those are things that you can find out be practicing! for example:
"activity" prefix may be not useful in case if all your layouts are for activities. but if there is bunch of other style (e.g dialog layouts) it could help to put "activity" prefix.
another example: I prefer to put "Activity" prefix for all classes that extends Activity, because eclipse shows classes base on name, and this could help to somehow a better management (but it's against Java naming convention! because you should suffix your class name with super class name)
For naming Id: You could prefix the resource with the name of what it is (e.g titleStatus), it doesn't really matters! but you for better managing your Ids and not losing in lots of name, always follow the same rule, if your name some element in your status like "statusTitle" the other element should be "statusDescription" but not "descriptionStatus"!

What is the best practice for naming the id of XML Element in Android?

I am not sure if anyone was bugged with this issue before, but it is one big pain for me.
How do you give an id to xml element in android?
Right now, I set the id with the pattern [activity/fragment name][element type][specific name]. For example, if I had an EditText to keep an email which is used in LoginActivity, I will give the id 'LoginEditTextEmail'.
The problem I'm facing is, with this approach, the id often ends up in a very long one.
How do you set the id? What is the best practice?
Descriptive names are ideal (same as with the name to any variable in any programming language).
I think you have a good system already I would offer these potential ways to decrease the size of your IDs
[activity/fragment name] - Personally I would drop this, I tend to use one layout file per activity / fragment anyhow so there is no confusing what activity the view is meant to be in. Also there are times when I re-use some View widgets in multiple activities and I will leave them with the same ID so that the code to find and interact them is simplified (i.e. it can be copy/paste or put into a subclass of Activity)
[element type] - I use a 3 letter shorthand for the widget types:
Edt = EditText
Txt = TextView
Lbl = TextView that is static for labeling something
Btn = Button
Prg = ProgressBar
Lyt = Layout
etc...
[specific name] - no real improvement to be made here, it has to be as long as it has to be to describe what it is for.
You're overcomplicating things. Just name it in whatever way is memorable to you. IDs only have to be unique per XML (i.e. you can have 50 different layouts with the id of my_edittext) since you find a view by it's ID only through a single view hierarchy.
Much like naming anything, I tend to use the shortest name possible that accurately describes it. In the case of ids for layouts, just make sure each id is unique in your layout (you can reuse the same id in a different layout).
Drop fragment, activity and type unless you qualify these in coding, so:
boolean isLoggedIn = false;
android:id="#+id/is_logged_in"
As mentioned in other responses the XML provides the qualifier, now you have to decide whether consistency and/or further qualification is necessary and if it befits. Do you really need to qualify and if you don't is supporting the code going to be a lot harder by you or anyone else?
So what about strings.xml?
prefix the id with a frag or activity qualifier. So, for example:
<string name="profile_is_logged_in_true">Logged in.</string>
<string name="profile_is_logged_in_false">Not logged in.%</string>
Also…
<plurals name="plural_is_logged_in_duration">...
I've toyed with:
<string name="profile_isloggedin_false">Not logged in.</string>
But not yet convinced. This is actually a classification problem, now since solved in other disciplines by tagging. Java provides dotted namespace and type qualifiers, so
com.example.android.app.profile.State.isLoggedIn
Android uses things like R.string :-) So you have the Java plus some additional namespace from Android. Don't forget you can have more than one string resources file, so perhaps:
res/values/widget_defaults.xml
could contain some default values for say a TextView. The true and false strings should be handled by plurals - but the example hopefully helps, despite a tad contrived.

what does the "#+android:id/title" mean?

In normal, we should use #+id/ to define an id and use #id to reference an id. Today I found #+android:id/title in apps/settings/res/layout/preferenc_progress.xml.
How to understand it and how to use it?
It is used for resources that are shipped with the SDK.
You can take a look at them by browsing to
[PATH TO ANDROID SDK]/platforms/android-[VERSION]/data/res
By using the android in android.R.whatever you just specify the R file to look up. For more information you should read Accessing Platform Resources.
That belongs to the app preferences activity screen definition.
title and summary are standard Android fields of a TextView preference item.
I think it does the same thing. It's just a more formal way of saying it by specifying where the namespace is.
I've never met this way of giving id, but in theory this means adding new id title to android package. So you'll be able to use it in your code like android.R.id.title. But I'm not sure resource compiler will really create any id in android package. I think it can be used only with predefined ids. But I'll give you more precise answer later, when I'll be able to check it.
EDIT: I've checked it and found some differences. Firstly, if you define Android's id using #+android:id/some_id, which is already present in SDK, this id will not be defined in your R.java file. If it's not present in SDK, it will be defined in R.java, but with different kind of value. Secondly, if you'll try to convert id from its string representation to int value, Resources.getIdentifier() method will return 0 in case of #+android:id format.
This means it will create an id in your resource file.

Layout files naming conventions?

What are some layout file naming conventions people have come up with.
I haven't found anything online, but thought about using the following convention.
What does everyone think?
- activity_*
- dialog_*
- list_item_*
That's all I have worked with so far.
Also, what about the naming of the activity against its layout? For example:
-> res
-> layout
-> activity_about_us.xml
-> src
-> activity
-> AboutUs.java
Strangely enough, trying to google this question brings only this page as meaningful result...
For the past half year I am using naming convention similar to yours but with shorter prefixes. For example:
For activity that shows "About us" screen:
Class name: ActAboutUs. Prefixing class is kind of overkill but it clearly distinguishes activity classes from the others. Initially I used separate directory for all the activities (similar to your approach) but after some time I realized that for bigger apps may be it is better to group in directories by feature than by superclass (i.e. Activity). It is easier for me to work in single directory for example /src/settings/ when I work on Settings. That way all java files that I need are in a single dir so i don't have to wander around:
/src/settings/ActSettingsGlobal.java
/src/settings/ActSettingsNet.java
/src/settings/Settings.java
/src/settings/SettingsDBAdapter.java
/src/settings/etc...
This approach also helps to split the work among different developers, i.e. each one is working in his own dir on separate feature so no stepping on each other's feet :-).
Some people preffer suffixes but I found them less useful. Prefixes help to group things alphabetically like in the example above: Act* prefix is sorted first so all activities are conveniently at the top.
I am even considering of using Act_ as a prefix which is more readable although it is in conflict with java naming conventions...
Layout filename: act_about_us.xml. In res/layout/ we don't have the "luxury" of subdirs which is quite unfortunate so the only way to group things is using appropriate prefix like act_, dlg_, etc...
String IDs: <string name="act_about_us_dlg_help1_title" ...
string.xml is the place where we have most problems with duplicate names. It is very easy to create duplicates if naming convention like activity_element_item is not used. It adds a lot of additional typing but it saves you from a lot of confusion later on.
For global (application wide) strings we use prefix "global_", for example global_btn_ok, global_msg_no_inet_conn. Usually we make one person responsible for all global_ strings so if someone needs new string or change he needs to sync with him in order to avoid creating a mess.
(now I am realizing that activity__element__item (two underscores) is more clear and readable than activity_element_item)
All in all I still can't get rid of the feeling that there is something wrong with my approach because I can't believe that google devs created such an inconvenient framework when it comes to working with files, IDs, names, etc...
i think following naming convention should be follow
for activity
if our activity name is
DisplayListActivity
then our layoutname should be
display_list_activity.xml
for list items we can include category in list item layout name
country_list_item.xml
and for dialogboxes their action can be included
delete_country_dialog.xml
When looking for a group of layouts, which is how I tend to work on them, I find it effective to always prepend the class name and follow up with any sub-layouts. For Instance:
Class Name: AboutActivity.java
Layout Name: about_activity.xml
Sub-layout Name: about_activity_menu.xml
Sub Sub-layout Name: about_activity_menu_item.xml
Your activity will always be at the top of each grouping and hunting for non-activities becomes less of a chore. Anyone know why sub-folders aren't a thing yet? I expect for efficiency and simplicity on the back-end, but I imagine it wouldn't hurt too much.
This is a good read https://jeroenmols.com/blog/2016/03/07/resourcenaming/
Basically, you follow WHAT WHERE DESCRIPTION SIZE
For example, layout file
activity_main: content view of the MainActivity
fragment_articledetail: view for the ArticleDetailFragment
strings
articledetail_title: title of ArticleDetailFragment
feedback_explanation: feedback explanation in FeedbackFragment
drawable
- all_infoicon_large: large version of generic info icon
- all_infoicon_24dp: 24dp version of generic info icon
The first part of a layout file name should always be the type of the corresponding class.
For example if we have a class MainActivity (type is Activity in this case), the corresponding layout file should be called activity_main.xml
That means that lets say we have a dialog called WarningDialog, the corresponding layout file should be called dialog_warning.xml, same goes for fragments etc.
This might seem familiar because thats also how the activity/layout files are named when creating a new project in Android Studio (MainActivity -> activity_main.xml).
For me, naming should fix two important requirements:
it should give you a hint about files' content and type (for example activity_login/login_activity or movie_list_item/list_item_movie)
it should visually group related items together to minimize jumping back and forth
For the second requirement, most people define "related" as type related which gives you something like this:
activity_login
activity_movie_list
activity_user_list
activity_settings
fragment_movie_list
fragment_user_list
item_movie
item_user
etc.
I prefer to do grouping by feature since you'll almost never work on all activities or all fragments, but instead, you'll work on movies feature or setting feature.
so, my prefered way is this:
login_activity
movie_list_activity
movie_list_fragment
movie_list_item
user_list_activity
user_list_fragment
user_list_item
settings_activity
Source files are following xml naming but in CamelCase, so there will be
LoginActivity
MovieListActivity
MovieFragment
etc.

Categories

Resources