androidandroid-viewandroid-custom-vieweditmode

What are the limitation in EditMode for custom views in Android?


I know how to use the View.isInEditMode method.

What I don't fully understand is when should I use it. That is, what should I prevent from running in EditMode.

There are the obvious cases, where the custom view does all kind of crazy things like DB access, networking, threads etc. where it is clear you should avoid them while in EditMode.

I created a several custom views that don't do anything of the above. They only use the regular drawing API, or load resources such as drawables.

When running on device they look exactly as expected, but inside the layout designer they either don't look as they should or even just fail to render due to some mysterious exception (Usually NullPointerException).

So, are there any limitations in EditMode on these APIs?


Solution

  • Custom views should work just fine as long as they only call parts of the view framework, not any application code. That's a good separation to have for views anyway: they should contain view state, not app logic.

    Typically you only have to use View#isInEditMode if your custom view is trying to access classes from its constructor (or measure or draw methods) where those calls for example try to access application framework code like say the FragmentManager. In that case you skip those calls with View#isInEditMode.

    It's hard to say more about what the problem you're seeing is without knowing more. In particular, what exactly is the NullPointerException you're seeing (full stack trace).

    It could also be a layoutlib bug. Try switching the render version (in the render toolbar) to a different version.