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:
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With