Manufacturing Unique R.id Values(转)

                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/

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值