How do you name UI elements? - android

I have been trying to find an answer to this question for months, but even Android documentation directs to Java naming convention document which does not say anything (which is logical) about Android-specific elements like TextView, EditView, etc. It also seems that stackoverflow does not have an answer to this question. Not to mention that Google demo projects use kindergarten namings, like myButton, yourEditView, theirTextView, etc. :)
So what document do you use as a source for Android-element naming convention? We've tried developing our own naming conventions, but it just did not feel right (we got ugly abbreviations).
We would like to create such document for our in-house usage, but we were stuck before we've even begun.

Are you referring to the ids in the xml layouts?
I name mine based on the layout name, type of view and functionality. For example if I have a signup.xml layout, I would name the elements inside:
[layout]_[view]_[object's purpose]
signup_text_user
signup_edit_user
signup_text_pass
signup_edit_pass
signup_btn_login
etc
The names are kind of long, but it's easy to look for the ids in code, since all my signup elements have a "signup_" prefix, and all my textviews inside the layout have "text_" and so on.

try this:
http://source.android.com/source/code-style.html#follow-field-naming-conventions

Related

Android naming convention

I am looking for a thorough Android naming convention suggestion.
I found a little bit here:
http://source.android.com/source/code-style.html#follow-field-naming-conventions
which says:
Non-public, non-static field names start with m.
Static field names start with s.
Other fields start with a lower case letter.
Public static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.
Yet I am looking for something much more extensive covering all aspects of Android:
how to name layouts and views within,
how to name menus
how to name styles
how to name database tables (singular, plural) and fields within
etc
If there is some generally accepted suggestion I would just love to follow that. All SDKs seem to go their own way so I am particular interested in the Android way to do it.
ribot's Android Guidelines are a good example of standard naming conventions:
Naming convention for XML files:
activity_<ACTIVITY NAME>.xml - for all activities
dialog_<DIALOG NAME>.xml - for all custom dialogs
row_<LIST_NAME>.xml - for custom row for listview
fragment_<FRAGMENT_NAME>.xml - for all fragments
Naming convention for component/widget in xml files:
All components for X activity must start with the activity name
all component should have prefix or short name like btn for Button
For example,name for login activity component should be like following.
activity_login_btn_login
activity_login_et_username
activity_login_et_password
Short name of major components:
Button - btn
EditText - et
TextView - tv
ProgressBar - pb
Checkbox - chk
RadioButton - rb
ToggleButton - tb
Spinner - spn
Menu - mnu
ListView - lv
GalleryView - gv
LinearLayout -ll
RelativeLayout - rl
This is an excellent collection of best practices to start with:
https://github.com/futurice/android-best-practices
Here's what I use. I'll also copy from that link.
Object naming
Don't use the m or s prefix as per Google guidelines. I've stopped for years and I find it easier without them. The IDE will tell you when you're using something private or static; it seems like an obsolete convention.
CONSTANTS start with caps
Acronyms should only capitalize the first letter. For example, functionUrl and unitId. Not unitID.
Prefix with the type of object. For example a TextView which contains a name would be tvName. An EditView with a password would be etPass.
If it's something usually used only once in an activity (e.g. ListView), don't be afraid to just call it lv.
If it's not an object type just name it by it's function. For example, if it's a string that holds the ID, name it as id, not stringId. The IDE will tell you when it's a string or a float or a long.
Keep it legible. Use something like Pass instead of Password.
Within the XML, name should be underscore with no capitals, e.g. tv_name and et_pass
Put the android:id as the first attribute in the XML.
File naming
Prefix layouts with the type it is. E.g. fragment_contact_details.xml, view_primary_button.xml, activity_main.xml.
For the classes, categorize them into folders, but use suffixes. For example, /activities/MainActivity.java or /fragments/DeleteDialog.java. My folders are activities, fragments, adapters, models, and utils.
Adapters should say how and when they are used. So a ListView adapter for ChatActivity might be called ChatListAdapter.
colors.xml and dimens.xml as a pallete
For color, use names like gray_light, not button_foreground.
For dimens, use names like spacing_large, not button_upper_padding.
If you want to set something specific for your button color or padding, use a style file.
strings.xml
Name your strings with keys that resemble namespaces, and don't be afraid of repeating a value for two or more keys.
Use error.message.network, not network_error.
Reasoning
The purpose of naming conventions is not to make everything neat and consistent. It's there to flag possible mistakes and improve workflow. Most of these are designed to be convenient for keyboard shortcuts. Try to focus around minimizing bugs and improving workflow rather than looking nice.
Prefixes are great for those, "What's the name of that TextView?" moments.
Suffixes are there for the things which you don't access so often in that manner, but can be confusing. For example, I may not be sure whether I put my code in the Activity, Fragment, or Adapter of that page. They can be dropped if you like.
XML ids are often in lowercase and uses underscores just because everyone seems to do it this way.
CONSISTENCY
Everyone (unless working in teams) will have their own convention and which one you choose does not matter. Making sure it is consistent throughout the whole application does matter.
STRUCTURE
Personally, I use a naming convention like this as it runs from the class name down to component and is consistent throughout the xml:
CLASS: <ClassName>
ACTIVITY: <ClassName>**Activity**
LAYOUT: classname_activity
COMPONENT IDS: classname_activity_component_name
An example of this would be OrderActivity.class, order_activity.xml, order_activity_bn_cancel. Notice all the XML is in lowercase.
ABBREVIATING LAYOUTS
If you would like to use shorter names to keep the code tidier; then another method can be to abbreviate ALL the names in XML aswell as the layouts.
An example of this would be OrderActivity.class: ord_act.xml, ord_act_bt_can, ord_act_ti_nam, ord_act_tv_nam. I break down the names into three but this depends how many similar names you have
ABBREVIATING COMPONENT TYPES
When abbreviating component types try to keep these consistent too. I normally use two letters for the component type and three letters for the name. However sometimes the name will not be necessary if that is the only element of that type in the layout. The principle of the ID is to be unique
COMPONENT IDS: nam_act_component_nam
COMPONENT TYPE ABBREVIATIONS (This list shows two letters which is plenty)
Frame Layout: fl
Linear Layout: ll
Table Layout: tl
Table Row: tr
Grid Layout: gl
Relative Layout: rl
Text View: tv
Button: bt
Check Box: cb
Switch: sw
Toggle Button: tb
Image Button: ib
Image View: iv
Progress Bar: pb
Seek Bar: sb
Rating Bar: rb
Spinner: sp
WebView: wv
Edit Text: et
Radio Group: rg
List View: lv
Grid View: gv
Expandable List View: el
Scroll View: sv
Horizontal Scroll View: hs
Search View:* se
Tab Host: th
Video View: vv
Dialer Filter: df
Include: ic
Fragment: fr
Custom View (other): cv
I don't think there is a convention for this yet . each company has its own rules and I don't think anyone cares much about it here.
For me , I prefer putting the name to be bound to the context . for example , if there is an activity called "MainActivity" , its layout name would be "main_activity.xml" , and for each resource associated with this activity , I add a prefix "main_activity" so that I know that it uses it . same goes for the ids used for this activity .
The reason I use those naming is that it's easier to find them, delete if needed , and you won't get them replaced with others if you use android libraries since the names are quite unique.
I also try as much as possible to give meaningful names , so you will usually not see "listView" or "imageView2" as ids , but something like "contactsListView" and "contactImageView" . the same name (or similar) would also match the variables inside the java code, in order to make it easier to find.
So , in short, my tips are:
try to avoid numbers inside the names . they usually don't mean much , and show that you've only used drag&drop for the UI designer .
for demos, POCs and for questions here , don't worry yourself about naming .
try to add a prefix to all of the names of the resources (including ids) to show which context they belong to , and to achieve uniqueness.
give meaningful names wherever possible .
The newest Android Eclipse plugins create some of the files you mention automatically when you create a new project. From that, the naming is something like that:
layout/activity_main.xml
menu/activity_main.xml
...
I followed this scheme with e.g.
layout/fragment_a.xml
layout/fragment_b.xml
...
So it's something like with package names, from general to detailed. It also allows for neat sorting.
As to naming conventions and/or best practices, I often follow this md file of ribot/android-guidelines repository in github that has project and coding guidelines enlisted in it.
Every body uses his own, The main goal is to avoid mistakes and misinterpretation, specially when others read your code. Though syntax highlighting, and auto code inspection in modern IDE's makes it pretty point less.
But these naming conventions also make it very convenient when code completion is turned on. For example just type m and auto complete will show you a list of class fields.
But many times you have to work with other's code, which doesn't use such convention. such protected variables and overridden method parameters just add to the confusion.
Few examples:
Prefix class variables with m , and make static finals variables all caps, with _ separating words. Don't prefix any thing to lower scope variables.
Name layout after the UI parent, for example act_main.xml , frg_detail.xml , itm__act_main__list1.xml ; for an activity MainActivity, a fragment DetailFragment, item layout for a ListView in MainActivity with id list1, respectively.
Name element Id's in xml layouts like: lsv__act_main__list1 for a ListView and btn__act_main__submit for a `Button element. This makes them much easier to find with auto complete.

Android: Naming Resources

This is a question for Android developers but it is not a programming-related question as it affects nothing but the developer.
What conventions are the most commonly used when naming various resources like colors, drawables and strings and etc?
I have no doubts naming my layouts activity_main or layout_secondary. However, I have always doubts when naming resources mentioned previously. I never know whether I should name these resources after their use or the content. For example:
Color: dark_blue vs text_highlighted
Drawable: blue_gradient vs top_bar_background
String: welcome_to_app vs first_time_prompt
Is there any community-created resource for good practice?
Naming is pretty much personal preference. The name is perfect as long as the name indicates what the functionality of the defined thing is. Also you and any other developer using these definitions should know how what the names mean and which definition to choose. Quite easy if you are consistent with names throughout the project.
For example dark_blue is obviously a blue color while text_highlighted is the color of highlighted text. The name you should use depends on what you need: if you want to classify colors by their name take the first, if you like to abstract from the actual color take the second. For general layouts using text_highlighted will often make more sense since the actual color does not matter and the functionality (text highlight vs text regular etc.) is more important. In this example choosing between text_highlighted and text_regular is a lot more obvious than choosing between color_light_blue and color_dark_blue although they could refer to the same color. The name can help prevent errors.
Android uses prefixes for names in [android.R.drawable]
(http://developer.android.com/reference/android/R.drawable.html) for example:
btn_ for button graphics
ic_ for icon graphics
ic_menu_ for menu icons
ic_dialog_ for dialog icons
stat_ for status icons
The schema is certainly not perfect but the advantage of using prefixes that start with the most generic classification is that you can use code completion to search for specific items step by step. So color_blue_dark could be better than dark_blue_color, at least if you consider the color classification more important than the dark / light classification. The same applies to first_time_prompt. If you have a lot of prompts it would make sense to name them prompt_first_time, promt_other_time, ... If they can be classified by an activity for example that could be used as super category: mainactivity_prompt_*, secondactivity_prompt_* so you know where they belong to.
Android SDK will be a good place to start for the good practices. You can open up any sample code in the SDK and go through the code and see the variable names.
I usually name assets like colors and pictures for their content, but I will name a style or multiple state drawable for it's function.
for example:
button_On.png; button_Off.png; button.xml
That way if I want to use the same resource in multiple places it does not get confusing.
For example using a color as a text color in one style file and a background in another style file.

CheckedTextView Attributes ID and checkMark

Just start developing with android and think instead of reading a book a webinar could be better because a webinar could also teach me short ways and how an android developer thinks when writing the code but now got a problem
<CheckedTextView
android:id="#android:id/text1"
android:checkMark="?android:attr/listChoiseIndicatorMultiple"
</>
I dont understand the above code up to now see lots of different id definitions some of them was for resources and start with #resource/name, and some of those id definitions was like #+id/name just for creating a new id for the component but this time it is using android:id/text1 and I dont understand why it is using it in that manner
Besides, the checkMark thing make me confuse more what are all those ?android:attr/listChoiseIndicatorMultiple means?
Could you please explain me and show me some resource where can I find all those magic attributes so I can cope next time by myself and hope someday can answer other newbie questions
Thanks a lot in advance, and all comment will be appreciated.
Well, reading the docs has always been helpful to me:
Android Developer Site
XML Layout specific docs
#android:id/text1 is just a format used when the id has been previously defined. When you put a + in there that means the framework should create the resource id if it doesn't already exist.
It's normal to use #+id/thisid when defining a new view in a layout, and then use #id/thisid to reference the aforementioned view from another part of the layout (say, in a RelativeLayout where you need to tell one widget to be below another).
A question mark before the ID indicates that you want to access a style attribute that's defined in a style theme, rather than hard-coding the attribute.
#android:id/text1 basically this is used when you create any android component like button, layout, textviews etc.
but when you need any external component which is general for different platform like any color, image etc then you can declare it as #resource/name.
actually there is nothing different just keep one thing in mind that in #android:id/text1, id will simply work as an class name will contains other objects like textview, imageview or any other.
now if you declare #resource/name then in that also instead of id class name will be resource. actually when you will use it in java then these(#android:id/text1) will be converted into object hierarchy.

Any way to organize android 's id "#+id/"

I am wondering is there a way to organize my widget's android:id . My app has a couple of Activies and couple of layout. It is hard to keep track of all the names of buttons and textviews. My IDE would spring up a list of all the R.id.xxx from previous layouts . Is there a way to sort them like with directory or periods, ie android:id="#+id/abc.efg" or android:id="#+id/abc/efg" . Sort of like sub structuring them or nesting them.
A simple way I keep track is by changing the "id" prefix to something else
ex.
A layout for ActivityOne might have layout IDs as
android:id="#+activity1/textview"
And "TestActivity" could be
android:id="#+test/textview"
I am trying to always use some convention on the id naming. For example use type-of-component prefixes: *btn_somethig* for all Buttons, *et_something* for all EditText and so on... When you're looking for a particular ID, just fill-in first the type of the component.
AFAIK no. I always go by a naming convention based on what I'm looking for. Usually it's, type_of_id_type_of_object_name. So a layout could be layout_relative_layout_main_panel. A sub-view like a TextView would be view_text_view_text1 or something. The detail is app-specific though.

Are there conventions on how to name resources?

Are there conventions how to name resources in Android? For example, buttons, textViews, menus, etc.
Android SDK will be a good place to start.
For example, I try to scope IDs within the activity.
If I had a ListView it simply would be #android:id/list in all the activities.
If, however, I had two lists then I would use the more specific #id/list_apple and #id/list_orange
So generic (ids, ...) gets reused in the R.java file while the unique ones (sometimes gets reused) get prefixed with generic ones separated by an underscore.
The underscore is one thing, I observed, for example:
Layout width is layout_width in xml and layoutWidth in code, so I try to stick to it as list_apple
So a Login button will be login, but if we have two logins then login_foo and login_bar.
I don't know whether there are any official recommendations.
For ids in my layouts with widgets and containers, I use the convention:
<layout>_<widget/container>_<name>
I do the same strategy for any dimens, strings, numbers, and colors I use in those layouts. However, I do try generalizing. e.g if all buttons have a common textColor, I won't prefix the name with the layout. The resource name would be 'button_textColor'. If all textColors are using the same the resource it will be named 'textColor'. For Styles, this is usually the case as well.
For menu resources i use:
menu_<activity>_<name>
Animations are only different as you cannot use uppercase letters. Same goes for drawable xml resources, i believe.
Taken from Android's documentation. There is more there on the subject.
To answer your question: Yes, there are.
You can find many of them via google search for example. And there is no such thing as the best naming convention. It always depends on your needs and your project attributes (most importantly the scope).
Recently, I've read quite good blog post about naming resources in Android XML from Jeroen Mols. Author mentions the basic principle all resources should follow and then how this convention is applied to each resource type. Both described on Android resource naming cheat sheet:
He then describes each element and each resource type in detail.
I would say you could use this convention from small to medium projects (personal use, few months contract applications). Although, I would not recommend it for long time projects with like 50+ activities or 1000+ strings.
Conventions for resource values in projects of such a large scale requires more investigation on how they will be used. Take strings for example. Might be affected by size of your team, translation center you are using (if any), VCS you are using (to avoid merge conflicts for example), etc. You might even think about splitting strings into multiple files.
I assume you are looking for something to begin with. So I would recommend the blog post I mentioned. It's good for starters and you can definitely use it as inspiration to create good naming conventions of your own.
Also keep in mind that as a project grows, many needs and requirements may change in time. So its completely normal that naming conventions that were suitable in the beginning will not be suitable after 2 years. And it's completely fine. You should not try to predict future. Just choose a convention and follow it. You will find if it is suitable for you and your project. If its not, think about why it is not suitable and start using something else.
There are a few conventions used in resources:
For resources that exist as separate files, they must be lower_case_underscore_separated. The appt tool makes sure that your files are only lower-case, because using mixed case can cause issues on case-insensitive filesystems.
For resources declared only in values/... (attributes, strings, etc) the convention is generally mixedCase.
There is a convention used sometimes to tag names with a "classification" to have simple namespaces. This is for example where you see things like layout_width and layout_alignLeft. In a layout file the attributes for both the View and the parent layout management are mixed together, even though they are different owners. The "layout_*" convention ensures that there are no conflicts between these names and it is easy to understand which entity the name impacts.
This "layout_blah" convention has also been used in a few other places. For example, there are "state_blah" attributes which are the drawable states a view can have.
Also because of these two conventions (underscore_separated for files, mixedCase for declared resources), you will find a number of inconsistencies. For example colors can be declared with either files or as explicit values. Generally we'd like to stick with underscore_separated for all of those, but it doesn't always happen.
Ultimately we don't worry a whole lot about naming conventions for resources. The big one that we keep consistent is "mixedCase" for attributes, and the use of "layout_blah" to identify layout param attributes.
Also browsing through the public resources here should give a good feel for the conventions:
http://developer.android.com/reference/android/R.html
You'll see the attributes are all quite consistent (given you understand the layout_ convention), drawables are all underscore_separated, etc.
This is a common problem to any language or framework, but so long as you avoid reserved words you should be ok assuming you can remember what you have called things.
I did note that Android places a restrction on xml resource file names but underscores seem to be ok. ADT actually states
File-based resource names must contain only lowercase a-z, 0-9, or _.
Something that tripped me up at first was a lack of namespaces with id's, but this can generally be ignored if you have two id's the same Android will just reuse the defined id.
For id's I use a 3 letter qualifier followed by what it refers to in camel notation e.g lblFoo for a static text label (or textview), txtFoo for an editable textbox (edittext in Android). This may seem odd at first but I've been using it since VB6 and those controls were called label and textbox.
Here are some more I commonly use:
btnFoo - button
pwdFoo - password
lstFoo - list
clrFoo - color
tblFoo - table
colFoo - column
rowFoo - row
imgFoo - image
dimFoo - dimension
padFoo - padding
mrgFoo - margin
I use the same in code within the java file too so I don't have to think about it, package scope will allow this quite happily:
Button btnFoo = (Button)findViewById(R.id.btnFoo);
You could if you prefer add a little spacing using underscore i.e btn_foo ... I probably would do this if I could break old habits.
There are those who may argue that abbreviating these may not be ideal and the purists would argue that the full name should be used, but when you are naming dozens of controls and changing between different systems and frameworks, the full names lose their meanings, I have used these for over a decade in VB, C++, ASP.NET, WinForms in C# and VB.NET, Android and Python. I never need to remember if Android calls it a textbox or an edittext. All I need to know is that lblFoo is the static label and txtFoo is what the user types input into.
One final note is that no matter what convention you decide upon the important things is naming controls properly and consistently, so that you don't wrestle with vague default id's e.g TextView5 or a mixture of different conventions
Useful link for designer and developers - here
Dimensions and sizes, naming conventions, styles and themes, nine-patch and so on.
I don't think there is any standard convention promoted by Google. I've seen all kinds of different ways people name stuff, even within different official Google apps.
Whatever helps you the most when trying to make sense of a 100 layout (or drawables, menus, etc.) files in one directory hierarchy.
A short answer: if you would like to learn from Android developers, a good example is the support library v7 (https://dl-ssl.google.com/android/repository/support_r21.zip)
Otherwise, here's what I have considered for naming resources:
1. finding resources easily when writing code
2. understanding resources easily when reading code
3. making names useful for translators (R.string.* resources only)
4. reusing layouts with <include/> (R.id.* resource conflicts)
5. dealing with library projects
Logically, arranging resources should be no different than grouping java classes into packages (or putting files into folders). However, since Android resources have no namespaces, prefixes must be added to the resource name to achieve the same (e.g. com.example.myapp.photo becomes com_example_myapp_photo).
I suggest to divide the app into separate components (activities, fragments, dialogs, etc.) with short unique names that can be used as resource prefixes. In this way we're grouping resources with related functionality together, which makes them easy to find (point 1) and we're at the same time avoiding naming conflicts with both <include/> and library projects (points 4 and 5). Note that resources common to multiple components can still have a prefix (such as R.string.myapp_ok_button).
After the prefix, the name should tell us what the resource is used for (action to be performed, content to be displayed, etc.). Choosing a good name is important for understanding (points 2 and 3).
Sometimes "component_name" will give us enough information, which is especially true if the type is already given by the R class (in R.string.myapp_name_string the 2nd "string" is redundant). However, explicitly adding type can improve understanding (e.g., it can be helpful for translators to distinguish between a toast, or a label). Sometimes the "name" and "type" parts can be swapped to allow type-based filtering (R.string.photo_menu_* will give us only menu-related items for the photo component).
Let's say we're writing an activity for taking pictures, class com.example.myapp.photo .PhotoActivity. Our resources could look like this (grouped by the component "photo"):
R.layout.photo //if only a single layout is used
R.menu.photo
R.string.photo_capture_instructions_label
R.id.photo_capture_instructions_label
R.id.photo_capture_button
R.id.photo_capture_image
R.drawable.photo_capture_placeholder
R.dimen.photo_capture_image_height
If you poke around in Android's documentation, there are various mentions of "best practices", but there are certainly no concrete rules. For example, in Icon Design Guidelines, Google suggests naming icons with a "ic_" prefix.
A good place to start may be Providing Resources.
Also dig around in the SDK source/examples as well as on the Android Developers Blog if you want to see how the Google developers do things.
I found handy next naming convention for strings:
[<action>]_<object>_<purpose>
For example, clear_playlist_text, delete_song_message, update_playlist_positivebutton_text. And "action" here is optional.
I generally followed the java naming conventions for resource ids(not for files for files) except I added "x" in front of the ids for example:
<TextView android:id="#+id/xTvName" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
In java
we can use it simple(we can also rememberin simple)
TextView mTvName=(TextView)findViewById(R.id.xTvName);
Here mTvName(It is in general android suggested naming conventions) and xTvName which was named in layout file as part of android TextView's Id(x meant for XML),I followed this type of naming conventions for view objects such as Buttons and EditText etc.
in XML IDS:xViewTypeSpecificName
in Java:mViewTypeSpeficName
The above conventions makes my life easier when I create complex layouts.
Just try to make your names as much as possible short in length and it is better if they are understandable and meaningful to other co-developers(but it may not possible every time),Hope that my experience will help others,suggestions are welcome.
In our android projects there are lots of components like buttons, labels, textboxes. So simple name like for example "name" this is very confusing to identify "name" is label or textbox. Mainly it happen when you are maintaining projects developed by some other developers.
So to avoid this kind of confusion I used following names for Buttons TextBoxes or Labels
Example :
btnName
labName
txtName
listName
May be this is helpful for you.
you can read the google documentation for code style to get an idea here
There are some restrictions:
Resource name should contains be a-z,0-9,_
Resource name should start with a-z,_
By the way, it is more advisable to follow the guidelines or to learn from standard code.

Categories

Resources