Aug 20, 2012

Know your resources: Integers and Booleans

An Android application isn't only code but comes with a bunch of resources. Probably the most important resources (besides layouts and drawables) are the string resources. In conjunction with the resource qualifiers they are not only perfect to externalize strings for localization but also for defining different internal configurations of your app.

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

1 comment:

  1. This is really handy for dimens. It handles the dp to px conversion and even the difference between size and offset.