However sometimes string resources are overused. Especially when they are used to define boolean or integer values. Let's look at the following example. Code lines like the next ones can be found in several Android projects. For example you can find some of these in Yaaic.
Loading string resources and parsing as boolean or integer |
Or even worse in a condition without casting, doing a string comparison:
Loading boolean as string resource and doing string comparison |
The code above is not wrong but instead of using string resources and parsing or comparing them it would be easier to use resources of the appropriate type. Fortunately Android allows to define boolean and integer resources too (since API level 1). It's basically the same process as defining a string resource in XML just use the bool and integer tags:
Defining boolean and integer resources in XML |
After that you can access these resources in code. However there are no alias methods on the Context object like for string resources. Therefore you need to get a Resources instance first and then ask it for the defined resources.
Accessing integer and boolean resources from code |
This is really handy for dimens. It handles the dp to px conversion and even the difference between size and offset.
ReplyDelete