Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of R.id values

I'm looking for ways to reduce what I would call "id pollution" in my apps. From what I can tell, R.id is global to the application, so in every Activity I usually create unique resource id values for elements, even if I have many of the same thing. For example, if I have three Activity classes, each with a save and cancel button, I would define six unique id's for R.id like:

R.id.actOne_save
R.id.actOne_cancel
R.id.actTwo_save
R.id.actTwo_cancel
R.id.actThree_save
R.id.actThree_cancel

This seems unnecessary to me, as I should really only need two running on any Activity. What are some of the practices that you all use when generating resource ids? Do you reuse them between activites? Is that OK if an id exists on two Activites (maybe one paused and one foreground) at the same time? I'm afraid of weird behavior like a button click hitting too many listeners!

like image 244
devunwired Avatar asked Sep 15 '10 15:09

devunwired


People also ask

What does R Id do?

Android R. java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains resource IDs for all the resources of res/ directory. Whenever you use any recourse in you project then its one Unique Id will be generated automatically and you can identify that resource by using that id.

What is r ID content?

The android. R. id. content ID value indicates the ViewGroup of the entire content area of an Activity .

What is the use of FindViewById in Android?

FindViewById(Int32)Finds a view that was identified by the android:id XML attribute that was processed in #onCreate .


2 Answers

You're fine to use the same id across multiple elements, as long as they aren't in the same view. So, all your save buttons could have the id of btn_save and as long as there aren't two of them in the same layout file, or attached layouts, then you're fine.

like image 146
Martyn Avatar answered Sep 22 '22 13:09

Martyn


I use:

R.id.activityName_type_action

where type may be [btn|txtview|edittext|listview...]

and action is something like [save|del|accept|name|pin...]

It's pretty verbose, but this way I can guess the identifier name from the activity without having to continuosly check the xml layout.

For example:

R.id.loginpin_btn_accept

R.id.loginpin_txtview_pin

like image 45
Maragues Avatar answered Sep 19 '22 13:09

Maragues