title: Patterns for custom view initialization compatible with layout preview
body: <p>I'm wondering if there are any good design pattern for initializing custom views (for example passing in a model/renderer). In particular I'm interested in patterns that allow for Android Studio layout preview to work (or something like <a href="http://jimulabs.com/" rel="nofollow">mirror</a> to work). </p>
  
  <p>For example take a simple game structure:</p>
  
  <p><strong>layout.xml</strong></p>
  
  <pre><code>&lt;LinearLayout&gt;
    &lt;com.package.GameSurface&gt;
  &lt;/LinearLayout&gt;
  </code></pre>
  
  <p><strong>GameSurface.java</strong></p>
  
  <pre><code>public class GameSurface extends View {
  
      int mComputedParam;
  
      Renderer mRenderer;
      GameState mGameState;
  
      public PlaySurface(Context context, AttributeSet attrs) {
          super(context, attrs);
      }
  
      public PlaySurface(Context context) {
          super(context);
      }
  
      // What are other ways of achieving this?
      public void init(GameState gameState, Renderer renderer) {
          mGameState = gameState;
          mRenderer = renderer;
      }
  
      @Override
      protected void onSizeChanged(int newWidth, int newHeight, int oldWidth, int oldHeight) {
          // Game state is used to calculate some layout/size/render information on the fly
          mComputedParam = (newWidth - getPaddingLeft() - getPaddingRight()) / mGameState.level();
      }
  
      @Override
      protected void onDraw(Canvas canvas) {
          super.onDraw(canvas);
  
          // Render can be swapped out based on level or user settings, etc
          mRenderer.draw();
      }
  
  }
  </code></pre>
  
  <p>Something like this will crash the Android studio layout preview since onDraw and onSizeChanged both throw null pointer exceptions if called without the <code>init()</code>. </p>
  
  <p>Would there be some other approach that makes this possible? Some ideas off the top of my head:</p>
  
  <ul>
  <li>Have a default renderer and model to fallback to in the layout preview. If this is a preferred solution, is there a way to detect that my code is being run in the layout preview?</li>
  <li>Have an option to choose the renderer via some sort of XML attribute, e.g. <code>custom:renderer="@values/default_renderer"</code> and then specify one for layout preview view <code>tools:renderer="@values/preview_renderer"</code>. It seems like there might <a href="http://tools.android.com/tips/layout-designtime-attributes" rel="nofollow">not be good support for this</a> (see Limitations section). This also might not work in some situations where instantiating the renderer couldn't easily be done in a static/preview context.</li>
  <li>Perhaps there's a way to run some setup code in the layout preview that I've overlooked?</li>
  </ul>