I've been wanting to make the code cleaner, but I do not give it away. I mean...
To name the ids of the views in the XML I use Hungarian notation like this:
<WHAT> <WHERE> <DESCRIPTION> <SIZE>
For example: tvExampleSectionEmptyBig,tvExampleSectionEmptySmall
Previously, using Butter Knife, I did not get too much coding because to do the bindings, I did things like this:
#BindView (R.id.tvExampleSectionEmptyBig) TextView tvEmptyBig;
#BindView (R.id.tvExampleSectionEmptySmall) TextView tvEmptySmall;
The code was much clearer and more reusable since the Hungarian notation used to avoid the confrontation between ids with the same name in different activities, fragments, etc. it was not present in practice more than in XML.
What's going on?
Kotlin has synthetic, which makes your life easier since with putting the id of the view, the binding is done directly, but with such long ids the code is very dirty ... Besides, makes sense that all the views I use in an activity called ExampleSectionActivity, contain within its variable nameExampleSection?
What would I like?
Surely there are better solutions that, but initially, what I feel is to implement a way to rename variables by removing a given String. As I follow a convention in all the names of the ids, it would be something internally in this way:
val tvEmptyBig = tvExampleSectionEmptyBig
val tvEmptySmall = tvExampleSectionEmptySmall
But of course, I would like to do it in an automated way.
On the other hand, I already tried naming the ids without the and to be careful with the imports, but for the moment synthetic fails very occasionally in this respect and I had to rebuild constantly. Especially if I open another instance of Android Studio, which I usually do quite often for consulting other projects I have.
Any idea? :-)
In my opinion, the easies and the most clean thing you can do is this:
private val myTextView: TextView
get() = f_layoyt_text_view
This way you don't have to use ridiculous, at least in 2018, ButterKnife and even more inconvenient findViewById.
For a few weeks, I already take for granted, that with the latest stable updates of Android Studio, there is no problem with repeating names of ids in different activities or fragments. Therefore, it is no longer necessary to put long variable names. Only there is to pay a little bit of attention to the imports, everything works like a charm, more readable and reusable. :-)
Related
Whenever we want to inflate a view or get a resource we have to cast it in run-time. views, for example, are used like so:
In the past, we would have needed to cast it locally
(RelativeLayout) findViewById(R.id.my_relative_layout_view)
Now, we use generics
findViewById<RelativeLayout>(R.id.my_relative_layout_view)
my question is why doesn't the compiler(or whoever generates the R class) doesn't also keep some kind of a reference to the type of the element(doesn't matter if it's a string or an int or any other type) that way casting problems should not occur
We cannot really speculate on that, that would be a design choice.
It might be that they wanted to avoid bloating the APK. Every ID would need a full package name to the class. So would each ID in android.R too. Since R is packaged in every APK.
Solutions
However, if you are using Kotlin, you can even do away with the generics check. Kotlin will determine it automatically.
val view = findViewById(R.id.my_relative_layout_view)
view.method()
Or event simpler, if you use synthetics:
my_relative_layout_view.method()
Also, if you are using data bindings, you can just access it like this:
binding.my_relative_layout_view.method()
I have just made my game app into a library so that I can incorporate it into a variety of "wrapper" projects, each with their own manifest file. This is so that I can easily maintain a variety of different versions e.g. free, paid, alternative markets etc.
I also wanted each wrapper to be able to affect the value of various boolean flags like include_adverts or allow_feature_x. I thought that a good way to do this (correct me if this is a dumb idea) would be for each wrapper project to have its own set of strings defined in its own strings.xml. So it could have things like:
<string name="allow_feature_x">true</string>
But now I have a problem scooping these strings from within the library.
I tried this:
boolean allow_feature_x = my_str2bool(getString(R.string.allow_feature_x));
But I get a allow_feature_x cannot be resolve error.
Can this strings.xml thing be made to work? Or was my scheme fundamentally flawed from the start?
This is exactly what I do for many of my projects.
Just make sure your library project has all the default set of strings defined in it, otherwise you won't be able to reference them, since the library does not know about the "parent".
Then override them in your "parent" projects. You only need to override the ones that are different from default, otherwise it will take the value from the library project.
Hope that makes sense.
Edit: By the way you can reference booleans like so:
<bool name="allow_feature_x">true</bool>
and then access getResources().getBoolean(R.bool.allow_feature_x);
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.
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.
I usually place my keys on an xml and access them with R.string.key_name but someone make me notice that I could have inline strings in the code.
I feel that I might use that key in different places and if I change its name I would just rename in the xml but perhaps that doesn't make too much sense with keys.
What do you think?
Your question conflates two different questions:
Does it make sense to have a single definition of your key?
Does it make sense for this single definition to be within an XML file?
The answer to point 1 is clearly "yes". Duplicating strings used as keys (which need to be the same everywhere for your code to function correctly) is a recipe for pain and heartache.
But what benefit does putting the key in an XML file give you? You're just adding "noise" to your code, and ensuring that whoever reads it has to find, understand and look in at least one additional file.
public static final is the way to go.
Inline literal strings will be a massive pain to change if they get scattered through the code. Localizing them in one place with either the strings.xml or a defining a public final static variable will probably save you a headache later.