ammar26
ammar26

Reputation: 1612

Is ID in XML cause the resource file builder to declare the instance in Android?

We mostly in android when working with layout file in XML declare the ID of those views/controls which we want to refer in the code or any else where in XML. I want to know what exactly Andriod performs at back-end

Upvotes: 0

Views: 71

Answers (1)

ydntn
ydntn

Reputation: 184

So let me explain here what really happens in the background.

We have the standard HashMap which has a key and a value The way the hash map works is by generating a hash-value out of the key which is used for mapping.

So, for example, if the strings.xml contains

<string name="app_name">Hello, Android</string>

The "app_name" is the key, which is hashed using some hash function and using that location the String "Hello, Android" is stored - the way normal Java HashMap works.

So lets go over this again

When you say map.get("app_name"); the hash function is called this way generatehash("app_name") and this value is used to calculate the position of the value(Hello, Android)

So every time we retrieve a value from this HashMap, we end up calling this generatehash() function - Although this is O(1), it is still some amount of processing. To make this little more efficient and spend lesser computing power (mobile devices are designed keeping very low memory foot-print in mind) - this generatehash() function is called only at compile time

That's the idea - so the hash-values are calculated at compile time and put up in this file called, R.java ... So at run-time, we have a one-on-one mapping of a key with the hash-value and this hash-value is directly used in finding the actual resource :)

So keeping this in mind, the resources are available "in-memory" at some particular location - just like a HashMap, and that location is calculated using the hash-value that is present in the R.java

Hope it answers your question.

Upvotes: 1

Related Questions