Friday, December 3, 2010

A Gotcha Moment with the View Attribute android:id

When editing layout xml files using Google's Eclipse plugin, the plugin is usually smart enough to flag typos when they cause code generation problems. However, errors that slip through the plugin undetected can cause nasty bugs at run-time. One such error involves the use of the attribute android:id. Usually, an id should be specified like this:

<!-- Correct Syntax -->
<Button android:id="@+id/abutton" />

But the following XML will compile fine without any error:

<!-- Incorrect Syntax -->
<Button id="@+id/xbutton" />

Android will even draw the button on the screen. The gotcha moment comes when you try to lookup this button in the view on a newer (such as Android 2.1) emulator/device:

Button aButton = (Button) thisView.findViewbyId(R.id.xbutton);

The aButton variable will be null after this call! What makes this a particularly hideous bug is that it was actually valid pre-Android 1.6! So apparently, the plug-in and the compiler are made backward compatible to allow the old syntax but not the run-time. Welcome to the bleeding edge...

No comments:

Post a Comment