As an extension of Android’s
R class, sbt-android introduces a the
TR class. It generates type safe mappings from ids in xml views to their respective class. This is explained best by a simple example:
Based on the xml view definition above, you will typically search for the
TextView by its id to specify the title at runtime. This is a very common use case, and in Java it works as shown below:
It is of course possible to do the exact same thing with Scala:
But thanks to
TR you can get rid of the cast and therefore simplify the code and improve type safety at the same time:
TR mappings are generated on every compile, when sbt-android detects changes in the class. Your IDE usually helps you to keep the
R up to date behind the scenes, but it won’t do that for the
TR class. You can still achieve a similar effect if you open your project sbt shell and run
~compile. The tilde before the command tells sbt to repeat this task whenever it detects a file change.
TR mappings only work for xml widgets that use the
android:id="@+id/xxx" property. If you chose not to use the
TR class you may want to disable it for performance reasons in your project’s sbt configuration via
typedResources := false.