Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

xml

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?

like image 876
Warut Surapat Avatar asked Jul 20 '12 14:07

Warut Surapat


2 Answers

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.

like image 106
FoamyGuy Avatar answered Oct 19 '22 21:10

FoamyGuy


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.

like image 43
Kevin Coppock Avatar answered Oct 19 '22 21:10

Kevin Coppock