Friday, 26 September 2014

Android Studio doesn't preview custom View

The Android Studio Layout Preview can be a powerful tool, but it still has his problems. Everything works perfectly fine while you stick to the default Android widgets, but with a custom widget you will likely incur in some kind of problem. In fact, sometimes your View is working perfectly at runtime, but it won't show in the preview.
You will get a stack trace like this one:

android.content.res.Resources$NotFoundException: Could not find attr resource matching value 0x7FFF0004 (resolved name: bar_thickness) in current configuration.

This could be caused by many factors, here are the two of them that I've found more annoying:
  • Using an OvalShape in your custom View
  • Using a resource in your View constructor
While the first one is currently an open bug, and not much can be done about it, the second one can be addressed with a workaround.

The Android View object provides a method to check if the View is being rendered in a preview tool, like the Android Studio one or like the eclipse plugin: isInEditMode(). This simply returns a boolean that states if the View is in a preview tool or not.

If you're using one or more resources in your View constructor you should replace them with fixed values when you're in edit mode.

For example this:

params.setMargins(getResources()
                    .getDimensionPixelSize(R.dimen.floating_label_left_margin), 0, 0, 0);


should become this:

 if (isInEditMode()) {
      params.setMargins(5, 0, 0, 0);

} else {
      params.setMargins(getResources()
              .getDimensionPixelSize(R.dimen.floating_label_left_margin), 0, 0, 0);

}