Wednesday, July 24, 2019

Detecting whether an Android ID is defined

I'm writing some test suites for student Android code. I'm trying to minimize the tests' compile-time dependencies on student code so that students can work on one part at a time without having compilable versions of everything. Some assignments ask them to set up layouts, in which view IDs create constants on R.id. The integer value of an ID constant can be looked up by name using the getIdentifier method of Resources. It can be called with all information in the first parameter...

resources.getIdentifier("com.example.app:id/theName", null, null)

...or with the resource type and package in separate parameters...

resources.getIdentifier("theName", "id", "com.example.app")

The return value is zero if the ID doesn't exist. That can be checked and used to throw a nice error message at runtime when that test is run rather than a compile error.

No comments:

Post a Comment