Manufacturing Unique R.id Values(转)

来源:互联网 发布:手机农村淘宝 编辑:程序博客网 时间:2024/05/01 18:29

                Manufacturing Unique R.id Values

 

If you have been developing in Android for any length of time, you’ll most likely be aware that one of the most useful portions the resource framework is the fact that Views and other resources can be given an android:id tag in their XML declaration, and Android will make sure to compile all the ids into unique integer values that can be accessed from Java code by calling R.id.. This allows us to reduce the number of event listeners an application requires because it can uniquely identify the view that triggered the event by matching its id.  And, of course, we prefer using integer ids for this as opposed to matching Objects or String tags because the ids fit nicely into switch statements!

 

For example, a layout with two buttons, both pointing at the same action method:

We can determine which button was pressed in the Activity by checking the sender’s id:

 

This is not breaking new, and is just one of many useful properties of android:id…
But what if we didn’t use XML to create our layouts/menus/etc.?  What if we created a series of Views in Java code?  Are we destined to go wanting without the assistance of the unique R.id generator?  Certainly not!

 

 Making id Elements Yourself

To reserve a set of ids for your own use in application, simply create an ids.xml file in the res/values directory of your project.  The syntax coupled with creating this file is pretty self-explanatory

res/values/ids.xml

 

Now let’s take these fresh ids and add them to a series Buttons created in a dynamic layout:

That’s it!  Just another practical application of a little known resource type in the Android framework.

 

Note: you can access this website: http://wiresareobsolete.com/wordpress/2011/04/manufacturing-ids/